Vaibhav
Vaibhav

Reputation: 1

How to update data programmatically in DataGridView using c#

In my dataGridView cells values are 0's and 1's. I have to set 0 to A and 1 to P by using following code for this operation.

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    int d = Convert.ToInt32(row.Cells[0].Value);
    if (d == 0)
        row.Cells[0].Value = "A";
    else
        row.Cells[0].Value = "P";
}

but it gives error, error is like

System.Exception: A is not a valid value for Int32. -> System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options NumberBuffer& number, NumberFormatinfo info, Boolean parseDecimal) at System.Number.Parselnt32(String s, NumberStyles style, NumberFormatinfo info) ... continue

If I set the numerical value in above program it update successfully but if I set string value like "A" or "P" it gives above error.

Please give me the solutions.

Upvotes: 0

Views: 791

Answers (2)

JohnG
JohnG

Reputation: 9469

In the future, to avoid this unnecessary back and forth inquisition, it would behoove you to include all the pertinent information in your question. Example in this case, the code that adds the data to the grid would benefit YOU by removing any question as to “how” the code is doing this. If others wanted to help you, then they are going to have to “guess” how this is done. If others (who you are asking help from) have to do a bunch of guessing and code writing to reproduce YOUR question… then most are going to move on.

I highly recommend that you take a look at the SO section on… How to create a Minimal, Reproducible Example ...I can not stress how helpful this “process” can be for YOU. Often times, the process of creating the “reproducible” example that you want to post here “reveals” the problem you are having. Posting a “complete reproducible example` will help you since the other people helping you don’t have to guess or write a bunch of code. Without question, you will get more and better answers to your questions if you do this simple thing.

As seen from the back and forth questions and answers, it seems to me that we are getting nowhere. Given your last comment, I am guessing you may be looking at this from the point of view of the DataGridView your comment…

”I have recently changed the column type in string by using code "dataGridView1.Columns[ 1 ].ValueType = typeof(string);". I have also confirm to print the column type by using code "Console.WriteLine(dataGridView1.Columns[1 ].ValueType);" before and after execution of the code "dataGridView1.Columns[1 ].ValueType = typeof(string);"”

Changing the “ValueType” IN THE GRID is fine, however, you need to keep in mind, that the “underlying” data source won’t necessarily respect/conform to the “GRIDS” value type. In fact in most cases, as this one… it WON’T. You can test this by doing the following steps:

1) Load the data into the grid such that the column we want to change is a “numeric” column.

2) Change that column to a string value type as your posted code does in your comment.

3) Type an “A” into the column you just changed to a string type then press the “Enter” key…

I am betting you will get a DataError exception.

It is true, your code changes the column type to a string IN THE GRID, but the underlying data source is still an int. Hence the DataError. The DataGridView simply displays the data that is in the data source. You can change the column types, format and order in the GRID, however, the underlying data source “usually” will NOT change. This is why, in your case, you need to “change” the column type in the data source, not the grid.

There are numerous ways to achieve this, however, IMHO I am betting the “easiest” way to do this would be to change the column type and possibly the values also “when you get the data from the data base.” I am aware this may not be an option at times and you are forced to make the changes you are asking for. But if you can do this directly from the data base, I recommend it.

Therefore, lets break down what I can gather you are asking. For starters, I assume you are getting the data from a data base and the data is returned in a DataTable. One of the columns in this DataTable is of some “numeric type” (‘intorDouble`) and it ONLY contains values of zeros (0s) and ones (1s). Is what you want, is to “change” the values in that column to “As” and “Ps” such that all zeros (0s) become “As” and ones (1s) become “Ps.” I hope I have this correct.

This appears straight forward, and I assume there are numerous ways to do this, however, I am confident you can NOT simply “change” a columns data “type” in an existing DataTable. Therefore, it seems obvious that your code is going to have to “ADD” this column to the existing DataTable. Something like…

originalDataTable.Columns.Add("A/P", typeof(string));

Then “after” the column as been added, loop through all the rows in the DataTable and set the values for the new “A/P” column. I am aware that this creates an extra column, however, it would be a simple task to remove or simply not display the column of 0s and 1s. Given this, a method Add_A_P_TextColumn(DataTable dt, string colName) … that takes a DataTable we want to add the column to and a string name to identify the column that contains the 0s, and 1s… may come in handy and look something like…

private void Add_A_P_TextColumn(DataTable dt, string colName) {
  dt.Columns.Add("A/P", typeof(string));
  foreach (DataRow row in dt.Rows) {
    row["A/P"] = (int)row[colName] == 0 ? "A" : "P";
  }
}

This should add the column as described and it is your choice to either remove the column of 0s and 1s or not. To demonstrate a complete and reproducible example, the complete code below demonstrates using the above method. To start, drop a DataGridView and a Button onto a form like below.

enter image description here

When the form loads, the code gets a column of random 0s and 1s for test data. This would be the original data your code gets from the data base. This is what the picture shows. When the user clicks the button, the Add_A_P_TextColumn method is called to add the "A/P" column.

DataTable OriginalTable;

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  OriginalTable = GetOriginalTable();
  dataGridView1.DataSource = OriginalTable;
}

private DataTable GetOriginalTable() {
  DataTable dt = new DataTable();
  dt.Columns.Add("0/1", typeof(int));
  Random rand = new Random();
  for (int i = 0; i < 15; i++) {
    dt.Rows.Add(rand.Next(2));
  }
  return dt;
}

private void button1_Click(object sender, EventArgs e) {
  Add_A_P_TextColumn(OriginalTable, "0/1");
}

I hope this clears some things up.

Upvotes: 2

Ilia S
Ilia S

Reputation: 1

you need to iterate over Cells as well:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    foreach(DataGridViewCell cell in row.Cells)
    {
        int d = Convert.ToInt32(cell.Value);
        if (d == 0)
           cell.Value = "A";
        else
           cell.Value = "P";
    }

}

Upvotes: 0

Related Questions