P.C P.C - 1 year ago 100
C# Question

How can I add text from textbox.Text to datagridview.CurrentCell when datagridview is filtered C#?

I'm not really good at coding and after doing countless research, I cannot figure this one out.

Basically what I want to achieve is to update a specific cell using a textBox. I wrote the following code based on other postings (NOTE:The DataBinding was done using the VS wizard):

int i;

private void textBox_TextChanged(object sender, EventArgs e)
i = dataGridView1.CurrentCell.RowIndex;

private void button1_Click(object sender, EventArgs e)
myDatabaseDataSet.Tables[0].Rows[i][5] = textBox.Text;

The problem with the above code is that, when I filter dataGridView1 with this code:

private void comboName_SelectedIndexChanged(object sender, EventArgs e)
DataTableCollection tables = myDatabaseDataSet.Tables;
DataView view1 = new DataView(tables[0]);
BindingSource source1 = new BindingSource();
source1.DataSource = view1;
dataGridView1.DataSource = source1;
source1.Filter = "Name='" + comboName.Text.Replace("'", "''") + "'";

The code will update the dataGridView1.CurrentCell.RowIndex as expected. The big problem here is that the code under button1_Click does not see the filtering, hence it would write -for example- in row[1] of the unfiltered table rather than in row[1] of the filtered table.

Any help would be greatly appreciated.

Answer Source

first off, you're gonna have to find a unique column that is unique for every row. then you can select the dataRow of your dataset based on that like this :

int uniqueIDFromDatagrid = (int)dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[uniqueIdentifierColumn.Index].Value;
DataRow targetRow = myDataSet.Tables[0].Rows.OfType<DataRow>().First(x => (int)x["uniqueIdentifierColumn"]== uniqueIDFromDatagrid);

and then you can update the source on the right row and column like this :

targetRow[5] = textBox1.Text;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download