当我们在ASP.NET应用程序中使用DataGridView控件时,我们通常需要实现增、删、改等数据交互操作功能。下面介绍具体实现方法:
一、创建数据库
选择合适的数据库系统,在其中创建一个表格,用于我们的演示。表格的结构如下:
CREATE TABLE [dbo].[Users](
[UserID] [int] IDENTITY(1,1) NOT NULL,
[Username] [nvarchar](50) NOT NULL,
[Password] [nvarchar](50) NOT NULL,
[Email] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED([UserID] ASC)
)
二、绑定DataGridView控件
在前端ASPX页面上添加一个DataGridView控件,并在后台代码中绑定数据源:
<asp:DataGridView ID="GridView1" runat="server"></asp:DataGridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
private void BindGridview()
{
string connString = ConfigurationManager.ConnectionStrings["conn"].ToString();
SqlConnection conn = new SqlConnection(connString);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Users", conn);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
三、实现添加新记录
在ASP.NET中,我们使用SqlCommand类执行SQL命令。下面是添加新记录的实现代码:
protected void btnSave_Click(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["conn"].ToString();
SqlConnection conn = new SqlConnection(connString);
string cmdText = "INSERT INTO Users (Username, Password, Email) VALUES (@UserName, @Password, @Email)";
SqlCommand cmd = new SqlCommand(cmdText, conn);
cmd.Parameters.AddWithValue("@UserName", txtUserName.Text);
cmd.Parameters.AddWithValue("@Password", txtPassword.Text);
cmd.Parameters.AddWithValue("@Email", txtEmail.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
BindGridview();
}
四、实现修改记录
DataGridView控件的默认编辑模式为“单元格”模式,而我们需要的是“行”模式。因此,我们需要在DataGridView的属性窗口中将EditMode属性设置为“EditOnKeystrokeOrF2”,可以在选中整行的情况下进行编辑。
当修改记录时,我们需要获取当前行的唯一标识 - UserID,以便于根据该标识修改数据库中的记录。下面是修改记录的实现代码:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string userID = GridView1.Rows[e.RowIndex].Cells[0].Text;
string userName = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string password = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
string email = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
string connString = ConfigurationManager.ConnectionStrings["conn"].ToString();
SqlConnection conn = new SqlConnection(connString);
string cmdText = "UPDATE Users SET Username=@UserName, Password=@Password, Email=@Email WHERE UserID=@UserID";
SqlCommand cmd = new SqlCommand(cmdText, conn);
cmd.Parameters.AddWithValue("@UserName", userName);
cmd.Parameters.AddWithValue("@Password", password);
cmd.Parameters.AddWithValue("@Email", email);
cmd.Parameters.AddWithValue("@UserID", userID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
GridView1.EditIndex = -1;
BindGridview();
}
五、实现删除记录
在删除记录时,我们需要获取当前行的唯一标识 - UserID,以便于根据该标识从数据库中删除记录。下面是删除记录的实现代码:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string userID = GridView1.Rows[e.RowIndex].Cells[0].Text;
string connString = ConfigurationManager.ConnectionStrings["conn"].ToString();
SqlConnection conn = new SqlConnection(connString);
string cmdText = "DELETE FROM Users WHERE UserID=@UserID";
SqlCommand cmd = new SqlCommand(cmdText, conn);
cmd.Parameters.AddWithValue("@UserID", userID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
BindGridview();
}
以上就是ASP.NET中使用DataGridView控件的增删改方法的具体实现,可以用于自己的项目中实现相应的功能。
下面是具体的代码示例:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataGridView.aspx.cs" Inherits="DataGridView" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="utf-8" />
<title>DataGridView Example</title>
<style type="text/css">
table {
border-collapse: collapse;
margin: 10px 0;
width: 100%;
}
table td, table th {
border: 1px solid #bbb;
padding: 4px;
text-align: center;
}
h2 {
margin: 30px 0 10px 0;
}
.add-new {
margin-bottom: 10px;
}
.edit-controls {
display: inline-block;
width: 100%;
}
.edit-controls input[type="text"] {
width: 100%;
margin-bottom: 5px;
}
.edit-controls input[type="button"] {
margin-top: 5px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<h2>DataGridView Example</h2>
<div class="add-new">
<input type="text" id="txtUserName" placeholder="Username" required />
<input type="text" id="txtPassword" placeholder="Password" required />
<input type="text" id="txtEmail" placeholder="Email" required />
<input type="button" id="btnSave" value="Save" onclick="btnSave_Click()" />
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" />
<asp:TemplateField HeaderText="Username" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblUserName" runat="server" Text='<%#Eval("Username")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<div class="edit-controls"><input type="text" ID="txtUserName" runat="server" value='<%#Eval("Username")%>' /></div>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Password" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblPassword" runat="server" Text='<%#Eval("Password")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<div class="edit-controls"><input type="text" ID="txtPassword" runat="server" value='<%#Eval("Password")%>' /></div>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email" ItemStyle-Width="200px">
<ItemTemplate>
<asp:Label ID="lblEmail" runat="server" Text='<%#Eval("Email")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<div class="edit-controls"><input type="text" ID="txtEmail" runat="server" value='<%#Eval("Email")%>' /></div>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
</Columns>
</asp:GridView>
</form>
<script type="text/javascript">
function btnSave_Click() {
var userName = document.getElementById("txtUserName").value;
var password = document.getElementById("txtPassword").value;
var email = document.getElementById("txtEmail").value;
if (userName == "" || password == "" || email == "") {
alert("Please enter all fields.");
return;
}
__doPostBack('<%=btnSave.ClientID %>', '');
}
</script>
</body>
</html>
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:asp.net中使用DatagridView的增删改方法具体实现 - Python技术站