hi all,
i would like to get the selected row from the datagrid and get the row's data to transfer it to textboxes.. how can i do this?
hi all,
i would like to get the selected row from the datagrid and get the row's data to transfer it to textboxes.. how can i do this?
Building on 's question and the replies from and : the easiest, most robust pattern is to handle the grid's selection event but avoid brittle numeric cell indexes when possible. Use DataKeyNames to carry the row's primary key and use FindControl to read controls inside TemplateFields. Falling back to cell text is OK for simple BoundFields, but remember command/select columns and empty cells can shift or break indexes.
Example (GridView SelectedIndexChanged — preferred):
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
// primary key (works when DataKeyNames="ID")
string id = GridView1.SelectedDataKey.Value.ToString();
// read a control placed in a TemplateField
var lblName = GridView1.SelectedRow.FindControl("lblName") as Label;
if (lblName != null)
TextBoxName.Text = lblName.Text;
else
TextBoxName.Text = GridView1.SelectedRow.Cells[2].Text.Replace(" ", "").Trim();
} Example (older DataGrid):
protected void DataGrid1_SelectedIndexChanged(object sender, EventArgs e)
{
var item = DataGrid1.SelectedItem;
TextBoxId.Text = item.Cells[1].Text.Replace(" ", "").Trim();
var lbl = item.FindControl("lblName") as Label;
if (lbl != null) TextBoxName.Text = lbl.Text;
} Quick checklist and pitfalls: set DataKeyNames on the grid; include a Select button or LinkButton with CommandName="Select" so selection fires; only call DataBind() when !IsPostBack or selection will be lost; check for null when using FindControl; handle " " from empty BoundFields. These steps expand on 's and 's suggestions and make row-selection more reliable across templates and postbacks.
Jump to Post— kvprajapati 1,826By passing integer index to the Rows collection you can select a row. A row is made up of Cells collection.
TextBox1.Text=GridView1.Rows[0].Cells[0].Text;
By passing integer index to the Rows collection you can select a row. A row is made up of Cells collection.
TextBox1.Text=GridView1.Rows[0].Cells[0].Text; U should over ride datagrid_selectedindexchanged method
in which get selectrow by something like following:
DataGrid.Rows[e.selectedindex].Cells[n].Text;
where n could be ur column number in a row as u know which column value u want to retrieve.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.