我有一个这样的GridView
<asp:GridView ID="gv_FilesList" runat="server" AutoGenerateColumns="false" onrowcommand="gv_FilesList_RowCommand">
<Columns>
<asp:BoundField DataField="f_Id" Visible="false" HeaderText="File Name" />
</Columns>
<Columns>
<asp:BoundField DataField="f_Name" HeaderText="File Name" />
</Columns>
<Columns>
<asp:ButtonField ButtonType="Link" Text="Download" CommandName="DownloadFile" HeaderText="Download" />
</Columns>
</asp:GridView>现在,当我单击download按钮时,我如何获得相应的f_Id以便从数据库中获取相关数据。
发布于 2010-10-25 21:31:54
这段代码应该可以工作,在我的本地进行了测试。
首先,将DataKeyNames添加到您的GridView。
<asp:GridView ID="gv_FilesList" runat="server" AutoGenerateColumns="false" onrowcommand="gv_FilesList_RowCommand" DataKeyNames="f_Id">
<Columns>
<asp:BoundField DataField="f_Id" Visible="false" HeaderText="File Name" />
</Columns>
<Columns>
<asp:BoundField DataField="f_Name" HeaderText="File Name" />
</Columns>
<Columns>
<asp:ButtonField ButtonType="Link" Text="Download" CommandName="DownloadFile" HeaderText="Download" />
</Columns>
</asp:GridView>然后,从代码后台访问DataKeys。
protected void gv_FilesList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DownloadFile")
{
//row index
int index = Convert.ToInt32(e.CommandArgument);
//retrieve f_Id
int f_Id = Convert.ToInt32(gv_FilesList.DataKeys[index].Value);
//download file with f_Id
DownloadFile(f_Id);
}
}发布于 2010-10-25 21:10:09
有几种方法可以给它换皮,但你可以像下面这样访问它:
void gv_FilesList_RowCommand(Object sender, GridViewCommandEventArgs e) {
if(e.CommandName=="DownloadFile")
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gv_FilesList.Rows[index];
string fileDownloadId = row.Cells[1].Text;
//Pull from DB
}然后将f_id添加到DataKeyNames属性,这样它将存储隐藏字段值。
<asp:GridView ID="gv_FilesList" runat="server" AutoGenerateColumns="false" onrowcommand="gv_FilesList_RowCommand" DataKeyNames="f_id">DataKeyNames
发布于 2010-10-25 21:09:04
您的问题的解决方案描述为in this thread。基本上,您可以在名为CommandArgument的事件参数属性中访问行索引。
https://stackoverflow.com/questions/4014758
复制相似问题