按钮单击行时,在C#Gridview中获取单元格值
我有一个gridviewMain。 每当我单击第1行的CLOSE linkbutton时,我想获得值aa。 单击第2行上的关闭获取bb的值。 有任何想法吗。
ABC aa xx 3 CLOSE bb yy 4 CLOSE cc zz 5 CLOSE
ASPX
假设您正在使用BoundFields
作为前三列,并且您想要处理LinkButton
-click事件(而不是GridView
RowCommand
):
protected void CloseLinkClicked(Object sender, EventArgs e) { var closeLink = (Control) sender; GridViewRow row = (GridViewRow) closeLink.NamingContainer; string firstCellText = row.Cells[0].Text; // here we are }
如果您正在使用TemplateFields
并且值aa
在Label中(例如LblValue
):
Label lblValue = (Label) row.FindControl("LblValue"); // lblValue.Text = "aa"
使用数据键。 更简单:
然后在代码隐藏中,只需获取与行关联的键:
var rowIndex = 0; var someValue = GridView1.DataKeys[rowIndex]["SomeValue"] as string;
您需要将CommandName
分配给GridView
标记中的LinkButton
列。 从那里你还需要连接OnRowCommand
事件来处理你的Close
命令。
以下是在GridView
上使用Add
命令的示例:
Markup: Code-Behind: void ContactsGridView_RowCommand(Object sender, GridViewCommandEventArgs e) { // If multiple buttons are used in a GridView control, use the // CommandName property to determine which button was clicked. if(e.CommandName=="Add") { // Convert the row index stored in the CommandArgument // property to an Integer. int index = Convert.ToInt32(e.CommandArgument); // Retrieve the row that contains the button clicked // by the user from the Rows collection. GridViewRow row = ContactsGridView.Rows[index]; // Create a new ListItem object for the contact in the row. ListItem item = new ListItem(); item.Text = Server.HtmlDecode(row.Cells[2].Text) + " " + Server.HtmlDecode(row.Cells[3].Text); // If the contact is not already in the ListBox, add the ListItem // object to the Items collection of the ListBox control. if (!ContactsListBox.Items.Contains(item)) { ContactsListBox.Items.Add(item); } } }
你可以这样做
CommandName="arg">Click
码
protected void grid_RowCommand(object sender, GridViewCommandEventArgs e) { int rowindex = int.Parse(e.CommandArgument.ToString()); ((TextBox)(grid.Rows[rowindex].FindControl("txtgvunit"))).Text }
参考http://dotnetinbox.blogspot.in/2014/02/get-gridview-row-data-in-c.html