我们知道在GridView中当我们单击按钮的时候,就会触发RowCommand 事件,因此我们可以通过使用此事件来获得Gridview控制中的值!
在GridView控件中的BoundField字段都有一个CommandName属性,通过获得它的属性值来判断我们单击的是那一列字段。
下面请看代码:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "add")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
ListItem item = new ListItem();
item.Text = Server.HtmlEncode(row.Cells[2].Text);
if (!ListBox1.Items.Contains(item))
ListBox1.Items.Add(item);
Label1.Text=e.CommandArgument.ToString();
}
}
在页面中添加了一个ListBox控件,通过单击Gridview控件中add按钮获取值并且添加到Listbox控件中去!{
if (e.CommandName == "add")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
ListItem item = new ListItem();
item.Text = Server.HtmlEncode(row.Cells[2].Text);
if (!ListBox1.Items.Contains(item))
ListBox1.Items.Add(item);
Label1.Text=e.CommandArgument.ToString();
}
}
注意:这里有个问题,不知道是不是我的问题,望知道的告诉我一下,row.Cell[2].text获取值必须要把BoundField字段转换成模板形式,否则获得的值是空值。但是转换成模板后就无法通过e.RowIndex获得该行的索引,这我们可以有另一种办法来通过GridView1.DataKeys[e.RowIndex].Values[0].ToString()来获得其值.
这里GridViewDeleteEventArgs的CommandArgument属性我们可以通过在 GridView1_RowCreated事件中设置值,然后在GridView1_RowDataBound中就可以通过e.RowIndex获得了!