ASP.NET 如何实现点击按钮后提取出指定GridView某行中各列的值?
现在页面上有一GridView,内有数据若干,每行数据后面有个按钮,点击相应行的按钮之后,将此行每列的值都取出来,存入数据库的某个表中,请问如何实现?我是新手。
[最优解释]
<asp:GridView ID="GridView1" runat="server" onrowcommand="GridView1_RowCommand"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Product" HeaderText="Product" />
<asp:BoundField DataField="Version" HeaderText="Version" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button" CommandArgument="<%# Container.DataItemIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("Product", Type.GetType("System.String"));
dt.Columns.Add("Version", Type.GetType("System.String"));
dt.Columns.Add("Description", Type.GetType("System.String"));
DataRow newRow;
newRow = dt.NewRow();
newRow["Product"] = "水果刀";
newRow["Version"] = "2.0";
newRow["Description"] = "打架专用";
dt.Rows.Add(newRow);
newRow = dt.NewRow();
newRow["Product"] = "折叠凳";
newRow["Version"] = "3.0";
newRow["Description"] = "行走江湖七武器之一";
dt.Rows.Add(newRow);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument.ToString());
string id= this.GridView1.Rows[index].Cells[0].Text;
}
经测试可行
[其他解释]
只要取到主键即可,然后把主键传入数据库中,
INSERT INTO XXX SELECT X0,X1,X3.... FROM TABLE WHERE ID=@ID
Refer this,
http://www.cnblogs.com/insus/archive/2011/06/30/2094151.html
[其他解释]
NamingContainer
Parent.Parent
DataKey
隐藏列
...
关键是取到该行的Index
[其他解释]
for(int i=0;i<gridview1.Rows.Count;i++)
{
response.Write(GridView1.Rows[i].Cells[0].ToString());
}
自己去修改一下就可以用了
[其他解释]
直接绑定要显示的数据;例如这里是Description
1:
<ItemTemplate> <%#Eval("Description")%>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" CommandArgument='<%# Eval("Description") %>' Text="发货" />
</ItemTemplate>
protected void Button2_Click(object sender, EventArgs e)
{
Button by = (Button)sender;
label11.Text = by.CommandArgument;
}
2:
<ItemTemplate>
<asp:Button ID="LinkButton1" runat="server" CausesValidation="False" CommandArgument='<%# Eval("Description") %>'
CommandName="delete_Command" Text="删除"></asp:Button>
</ItemTemplate>
protected void delete_Command(object sender, CommandEventArgs e)
{
string ID = e.CommandArgument.ToString();//取得要插入数据库的数据
}