Sunday, April 19, 2009

C# - How to bind a TextBox to a DataGridView column

The goal is "bind a TextBox to a column in a DataGridView control" to be able to edit the cell in that columns for each rows and also show the value of the cell in that column when user move through the grid rows.

In the following code, imagine that we have a DataGridView called dgvTst and a TextBox control that called txtTst. To bind, CellClick event of DataGridView is coded as following:

private void dgvTst_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (txtTst.DataBindings.Count > 0)
txtTst.DataBindings.RemoveAt(0);

// The code binds column index 2 to the TextBox control
txtTst.DataBindings.Add(
new Binding("Text", dgvTst[2, e.RowIndex], "Value", false) );
}


Share/Bookmark

2 comments:

Tanhaeyaan said...

hello Friend,
I want to need Textbox Data Binding help as your given code , I am tried to build Form. my problem is, i have two form Ist one using for watching update Datagridview and 2nd is data entries with help Textbox but update command are unable to update Ist Form DataGridview, Can you give me some help for this topic
thanks
With Regards
Amit Kumar

스키너 부국장's 그림일기장 @ Google said...

thxs