TimmRH TimmRH - 10 months ago 62
C# Question

Using DataGridView in Visual Studio C#

I have a string that contains: "# of rows, # of columns, Row'X'Col'X'=Serial#, ...

How do I create a DataGrid table with the number of rows and columns defined, and then place the serial #s into the grid.





Answer Source

Below is code that does what you are asking; however I must point out some problems with this approach. First, getting the total rows and cols from the first two elements in order to create your table is risky. If that data is wrong, this code will most likely crash or possibly omit data. Example if the input is: 2,2,RXCX=.., RXCX=.., RXCX=.., RXCX=..,RXCX=, RXCX=… This line will only get the first 4 values.

Worse… this will crash… if the input is 2,2,RXCX=.., RXCX=.. Then it will crash when you try to access the 4th element in the splitArray because there isn’t a 4th element. Either way is not good.

My point is to be safe… it would be a better approach to see how much data is actually there before you create the grid. You could get how many items there are with StringArray.Length minus the first two elements. These elements will define the dimensions and allow you to check their validity. This will make sure your loops won’t go out of bounds because the supplied data was wrong. It seems redundant and error prone to supply the dimension values when you can get that info from the data itself.

I still am not 100% sure what you want to accomplish here. It looks like a search of some form. This is what I am picturing… Looking at your (previous) screen shots it appears to me that after you type into the Serial # text box and click the “Search Txt Files” button it will search for data that came from the input string i.e. “PLX51…” and then have the grid display the “filtered” results that match (or are LIKE) what’s in the Serial # textbox. If this is true, I would ignore the RXCX vales and put the data in a single column. Then wire up an OnKeyPress event for the text box to filter the grid whenever the user types into the Serial # text box. Otherwise I am lost as to why you would need to create the data in the fashion described. Just because the input has unnecessary data… doesn’t mean you have to use it. Just a thought.

  string inputString = "2,2,R1C1=211,R1C2=212,R2C1=213,R2C2=214";
  string[] splitArray = inputString.Split(',');
  int totalRows = int.Parse(splitArray[0]);
  int totalCols = int.Parse(splitArray[1]);
  int itemIndex = 2;

  // add the columns
  for (int i = 0; i < totalCols; i++)
    dataGridView1.Columns.Add("Col", "Col");
  // add the rows

  for (int i = 0; i < totalRows; i++)
    for (int j = 0; j < totalCols; j++)
      dataGridView1.Rows[i].Cells[j].Value = splitArray[itemIndex];