如何获取网格视图中单击按钮行的数据
本文关键字:单击 按钮 数据 视图 网格 何获取 获取 | 更新日期: 2023-09-27 18:21:39
我正在构建一个站点,但出现了问题。我不知道如何访问单击按钮所在行的网格数据。
.aspx文件:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlEntry"
CssClass="style1">
<Columns>
<asp:BoundField DataField="ReordID" HeaderText="ReordID" InsertVisible="False" SortExpression="ReordID"
Visible="False" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="EmailID" HeaderText="EmailID" SortExpression="EmailID" />
<asp:BoundField DataField="Password" HeaderText="Password" SortExpression="Password" />
<asp:TemplateField HeaderText="Delete" SortExpression="Delete">
<ItemTemplate>
<asp:Button Text="Delete" runat="server" OnClick="Grid_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="Gray" />
<AlternatingRowStyle BackColor="#CCCCCC" />
</asp:GridView>
<asp:SqlDataSource ID="SqlEntry" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Entry]"></asp:SqlDataSource>
.CS文件:
protected void Refresh_Click(object sender, EventArgs e)
{
GridView1.DataBind();
resetdata();
}
protected void Submit_Click(object sender, EventArgs e)
{
string str = "INSERT INTO Entry (Name, EmailID, Password) VALUES ('" + TextBox1.Text.Trim() + "','" + TextBox2.Text.Trim() + "','" + TextBox3.Text.Trim() + "');";
Connection conn = new Connection(str);
Refresh_Click(sender, e);
}
protected void resetdata()
{
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
}
protected void Grid_Click(Object sender, EventArgs e)
{
string str = "DELETE FROM Entry WHERE RecordID = @RecordID";
Connection conn = new Connection(str);
GridView1.DataBind();
resetdata();
}
连接类别:
public Connection(string qry)
{
SqlConnection con = new SqlConnection(@"Data Source=.'SQLEXPRESS;AttachDbFilename=|DataDirectory|'Database.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = qry;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
如何使用此网页从SQLServer2005中删除数据?代码中的问题是什么?
您可以将CommandArgument
和CommandName
附加到包含ID-的按钮上
<ItemTemplate>
<asp:Button Text="Delete" runat="server" CommandArgument="<%# Eval('ReordID') %>" CommandName="REMOVE" OnClick="Grid_Click" />
</ItemTemplate>
然后将RowCommand
事件添加到GridView-
void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="REMOVE")
{
int orderId = Convert.ToInt32(e.CommandArgument);
//Do Sql Here
}
}