asp.netgridview增删改查
时间: 2023-09-15 11:19:03 浏览: 95
ASP.NET GridView控件是一个非常强大且广泛使用的控件,可以用于实现数据的绑定、编辑、删除、分页等功能。下面是ASP.NET GridView控件的增删改查示例代码:
1.绑定数据:
```html
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
<asp:CommandField ShowEditButton="True" ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [Table]"></asp:SqlDataSource>
```
2.添加数据:
```csharp
protected void btnAdd_Click(object sender, EventArgs e)
{
string name = txtName.Text.Trim();
int age = int.Parse(txtAge.Text.Trim());
string sql = "INSERT INTO [Table] (Name, Age) VALUES (@Name, @Age)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Age", age);
conn.Open();
cmd.ExecuteNonQuery();
}
}
GridView1.DataBind();
}
```
3.编辑数据:
```csharp
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int id = int.Parse(e.Keys["ID"].ToString());
string name = e.NewValues["Name"].ToString();
int age = int.Parse(e.NewValues["Age"].ToString());
string sql = "UPDATE [Table] SET Name = @Name, Age = @Age WHERE ID = @ID";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Age", age);
cmd.Parameters.AddWithValue("@ID", id);
conn.Open();
cmd.ExecuteNonQuery();
}
}
GridView1.EditIndex = -1;
GridView1.DataBind();
}
```
4.删除数据:
```csharp
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = int.Parse(e.Keys["ID"].ToString());
string sql = "DELETE FROM [Table] WHERE ID = @ID";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@ID", id);
conn.Open();
cmd.ExecuteNonQuery();
}
}
GridView1.DataBind();
}
```
注意:以上代码中的[Table]和ConnectionString需要根据实际情况进行修改。
阅读全文