asp.netgridview增删改查
时间: 2023-09-15 11:19:02 浏览: 162
ASP.NET GridView 控件提供了方便的数据绑定和展示功能,同时也支持常见的增删改查操作。以下是实现 GridView 增删改查的基本步骤:
1.绑定数据源:将数据源与 GridView 控件进行绑定。
```csharp
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string connectionString = "your connection string";
string selectCommand = "SELECT * FROM yourTable";
SqlDataAdapter dataAdapter = new SqlDataAdapter(selectCommand, connectionString);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
GridView1.DataSource = dataSet.Tables[0];
GridView1.DataBind();
}
}
```
2.实现新增功能:在 GridView 控件中新增一条记录。
```csharp
protected void btnAdd_Click(object sender, EventArgs e)
{
string connectionString = "your connection string";
string insertCommand = "INSERT INTO yourTable (col1, col2, col3) VALUES (@val1, @val2, @val3)";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(insertCommand, connection);
command.Parameters.AddWithValue("@val1", txtVal1.Text);
command.Parameters.AddWithValue("@val2", txtVal2.Text);
command.Parameters.AddWithValue("@val3", txtVal3.Text);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
GridView1.DataBind();
}
```
3.实现修改功能:在 GridView 控件中修改一条记录。
```csharp
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string connectionString = "your connection string";
string updateCommand = "UPDATE yourTable SET col1 = @val1, col2 = @val2, col3 = @val3 WHERE id = @id";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(updateCommand, connection);
command.Parameters.AddWithValue("@val1", e.NewValues["col1"]);
command.Parameters.AddWithValue("@val2", e.NewValues["col2"]);
command.Parameters.AddWithValue("@val3", e.NewValues["col3"]);
command.Parameters.AddWithValue("@id", e.Keys["id"]);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
GridView1.EditIndex = -1;
GridView1.DataBind();
}
```
4.实现删除功能:在 GridView 控件中删除一条记录。
```csharp
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string connectionString = "your connection string";
string deleteCommand = "DELETE FROM yourTable WHERE id = @id";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(deleteCommand, connection);
command.Parameters.AddWithValue("@id", e.Keys["id"]);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
GridView1.DataBind();
}
```
以上是实现 ASP.NET GridView 增删改查的基本步骤,具体实现可以根据实际情况进行调整。
阅读全文