Updating DataGridView
Hi
I have a data grid view whose data source is a data table from an xml file.
Now what i want to do is this:
Display all the column except the last column say col5 which i hide with col5.visible = false
Now the UI has a text box where i show the contents of column col5. Now when i select the data table , the text box must get updated with the text in the column and when i save the data table , the text in the text box must get written into the table. How do i do this ?
I did some trials two of them like this but did not help much :
1.
dataGridView1[1,ClickedRowIndex].Value = richTextBox1.Text;
2.
DataTable dt = (DataTable)dataGridView1.DataSource;
dt.AcceptChanges();
dt.WriteXml(file);
Thanks for glancing !
Nilanka DharmadasaPosted Jan 20, 2010, 8:24 AM
First you use the CellClick event of dataGridView to get the value of the last column of the currenct row. Then you can set it to textbox.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.RowIndex >= 0)
{
string s = dataGridView1.Rows[e.RowIndex].Cells[dataGridView1.Columns.Count - 1].Value.ToString();//Get the last column value
richTextBox1.Text = s;
}
}
catch
{
}
}
Then you can use Leave event of textbox to get the value of the textbox and set it to the last column of the current row of datagridview.
private void richTextBox1_Leave(object sender, EventArgs e)
{
try
{
if (dataGridView1.CurrentRow != null)
{
if (dataGridView1.CurrentRow.Cells[dataGridView1.Columns.Count - 1] != null)
dataGridView1.CurrentRow.Cells[dataGridView1.Columns.Count - 1].Value = richTextBox1.Text;
DataTable dt = (DataTable)dataGridView1.DataSource;
dt.AcceptChanges();
}
}
catch
{
}
}
Now when you save the datatable to xml, the values you typed will be saved to the xml.
If my answer helps, do not forget to tick 'Do you like this answer' checkbox.