<Columns>
<asp:TemplateField HeaderText="模版列选择">
<ItemTemplate>
<asp:LinkButton ID="lbkID" runat="server" CommandName="chooseModel" >选择</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="choosecol" HeaderText="不是模版列的选择" Text="选择" />
<asp:BoundField DataField="name" />
</Columns>
<asp:TemplateField HeaderText="模版列选择">
<ItemTemplate>
<asp:LinkButton ID="lbkID" runat="server" CommandName="chooseModel" >选择</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="choosecol" HeaderText="不是模版列的选择" Text="选择" />
<asp:BoundField DataField="name" />
</Columns>
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "chooseModel")
{
//会出错
string i = Convert.ToString(e.CommandArgument);
}
if (e.CommandName == "choosecol")
{
//不会出错
string i = Convert.ToString(e.CommandArgument);
// Response.Write(i);
}
}
{
if (e.CommandName == "chooseModel")
{
//会出错
string i = Convert.ToString(e.CommandArgument);
}
if (e.CommandName == "choosecol")
{
//不会出错
string i = Convert.ToString(e.CommandArgument);
// Response.Write(i);
}
}
发现如果在模版列使用了e.CommandArgument 程序会报错!
但在其他列里是可以用的!
模板列里放的控件的 CommandArgument 属性设置下值 ,没设置的话好像取不到
CommandArgument ="<%# GridView1.Rows.Count %>"
protected void GridViewIw1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "chooseModel")
{
int index = Convert.ToInt32(e.CommandArgument);
string CID = GridViewIw1.DataKeys[index].Value.ToString();
}
}
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" DataKeyNames="id"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:ImageButton ID="ibtnOK" runat="server" CommandName="OK" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
- C# code
-
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "OK") { int index = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).RowIndex; //通过下面的方式找到当前行主键 string id = GridView1.DataKeys[index].Value.ToString(); //然后做你的数据库操作 } }