问:我是asp.net mvc的初学者,目前正在asp.net项目上工作。请告诉我如何使用C#在ASP.Net的GridView中插入,删除,更新。
我将衷心感谢您的帮助。
答:请按照以下步骤了解如何在ASP.NET中使用GridView。
步骤1:- 在SqlServer中创建一个数据库,并在该数据库中创建一个表。为了进行演示,我创建了一个名为“ Demo”的数据库和一个名为“ GridView ”的表
CREATE DATABASE DEMO
GO
USE DEMO GO CREATE TABLE GridView控件(ID INT PRIMARY KEY身份,名称 VARCHAR (50 )NOT NUL
第2步:-在应用程序的web.config文件中添加连接字符串,并根据以下SQL Server配置更改名称和connectionString。
<configuration>
<connectionStrings>
<add name =“ dbconnection” providerName =“ System.Data.SqlClient”
connectionString =“ Data Source = .;初始目录= demo;用户ID = xyz; password = 123456” />
</ connectionStrings>
</ configuration>
步骤3:- 从“ 工具箱”中 拖放GridView控件。aspx ” 页面,并在<asp: GridView>部分中写下以下代码行, 或者简单地复制以下代码行并将其放置在要显示 G ridView的位置。
< div >
< asp :GridView ID =“ GridView1” runat =“服务器” ShowHeaderWhenEmpty =“ True” AutoGenerateColumns =“ False” onrowdeleting =“ RowDeleting” OnRowCancelingEdit =“ cancelRecord” OnRowEditing =“ editRecord” OnRowUpdating =“ updateRecord” CellPadding =“ 4“ EnableModelValidation =” True“ GridLines =” None“宽度=” 1297px“ ForeColor =”#333333“ > <RowStyle HorizontalAlign =“ Center” />
< AlternatingRowStyle BackColor =“白色” /> < EditRowStyle BackColor =“#7C6F57” /> < FooterStyle BackColor =“#1C5E55” ForeColor =“白色” Font-Bold =“ True” /> < HeaderStyle BackColor =“#1C5E55”字体-粗体=“ True” ForeColor =“ White” /> < PagerStyle BackColor =“#666666” ForeColor =“ White” HorizontalAlign =“ Center” />< RowStyle BackColor =“#E3EAEB” />
< SelectedRowStyle BackColor =“#C5BBAF” Font-Bold =“ True” ForeColor =“#333333” /> <列> < asp :TemplateField > < HeaderTemplate > ID </ HeaderTemplate > < ItemTemplate > < asp :标签 ID =“ lblId “ runat =”服务器“文本=' <%#Bind(” id“)%> '> </ asp :标签> </ ItemTemplate
>
</ asp :TemplateField > < asp :TemplateField > < HeaderTemplate >名称</ HeaderTemplate > < ItemTemplate > < asp :标签 ID =“ lblName” runat =“ server” Text =' <%#Bind(“ name”) % > '> </ asp :标签> </ ItemTemplate > < EditItemTemplate > <asp :
TextBox ID =“ txtName” Runat =“服务器” Text =' <%#Bind(“ name”) %> ' MaxLength =“ 50”> </ asp :TextBox > < asp :RequiredFieldValidator ID =“ rfvtxtName” runat =“服务器“文本=” *“工具提示=”输入名称“ ControlToValidate =” txtName“> </ asp :RequiredFieldValidator > < asp :的RegularExpressionValidator ID = “revtxtName” RUNAT
=“服务器”文本=“ *”工具提示=“输入alphabate
“ ControlToValidate =” txtName“ ValidationExpression =” ^ [a-zA-Z'。\ s] {1,40} $“> </ asp :RegularExpressionValidator > </ EditItemTemplate > < FooterTemplate > < asp :文本框 ID =” txtNewName “ runat =”服务器“ MaxLength =” 50“> </ asp :文本框> < asp :RequiredFieldValidator ID =” rfvtxtNewName“ runat =”服务器“文本=” *“ToolTip =“输入名称”
ControlToValidate =“ txtNewName”> </ asp :RequiredFieldValidator >
< asp :RegularExpressionValidator ID =“ revtxtNewName” runat =“ server” Text =“ *” ToolTip =“ Enter alphabate
“ ControlToValidate =” txtNewName“ ValidationExpression =” ^ [a-zA-Z'。\ s] {1,40} $“> </ asp :RegularExpressionValidator > </ FooterTemplate > </ asp :TemplateField > < asp :TemplateField > < HeaderTemplate >年龄</ HeaderTemplate > < ItemTemplate > < asp :标签 ID =“ lblAge” runat =“ server” Text ='<%#绑定(“年龄”)
%> '> </ asp :标签>
</ ItemTemplate > < EditItemTemplate > < asp :TextBox ID =“ txtAge” runat =“ server” Text =' <%#Bind(“ age”) %> ' MaxLength =“ 2 “> </ asp :文本框> < asp :RequiredFieldValidator ID =” rfvtxtAge“ runat =”服务器“文本=” *“ToolTip =“输入年龄” ControlToValidate
=“ txtAge”> </ asp :RequiredFieldValidator >
< asp :RegularExpressionValidator ID =“ revtxtAge” runat =“ server”文本=“ *” ToolTip =“输入数字
值“ ControlToValidate =” txtAge“ ValidationExpression =” ^ [0-9] + $“> </ asp :RegularExpressionValidator > </ EditItemTemplate > < FooterTemplate > < asp :TextBox ID =” txtNewAge“ runat =”服务器“ MaxLength =” 2“> </ asp :文本框> < asp :RequiredFieldValidator ID =” rfvtxtNewAge“ runat =” server“文本=” *“ToolTip =“输入年龄” ControlToValidate
=“ txtNewAge”> </ asp :RequiredFieldValidator >
< asp :RegularExpressionValidator ID =“ revNewtxtAge” runat =“ server”文本=“ *” ToolTip =“输入数字
值“ ControlToValidate =” txtNewAge“ ValidationExpression =” ^ [0-9] + $“> </ asp :RegularExpressionValidator > </ FooterTemplate > </ asp :TemplateField > < asp :TemplateField > < HeaderTemplate >工资</ HeaderTemplate > < ItemTemplate > < asp :标签 ID = “ lblSalary” runat =“服务器” Text ='<%#
Bind(“ salary”) %> '> </ asp :标签>
</ ItemTemplate > < EditItemTemplate > < asp :TextBox ID =“ txtSalary” runat =“ server” Text =' <%#Bind(“ salary”) % > ' MaxLength =“ 10”> </ asp :文本框> < asp :RequiredFieldValidator ID =“ rfvtxtSalary” runat =“ server”文字=“ *”工具提示=“输入薪水”
ControlToValidate =“ txtSalary”> </ asp :RequiredFieldValidator >
< asp :RegularExpressionValidator ID =“ revtxtSalary” runat =“ server”文本=“ *” ToolTip =“输入数字
值“ ControlToValidate =” txtSalary“ ValidationExpression =” ^ [0-9] + $“> </ asp :RegularExpressionValidator > </ EditItemTemplate > < FooterTemplate > < asp :TextBox ID =” txtNewSalary“ runat =” server“ MaxLength =” 10“> </ asp :文本框> < asp :RequiredFieldValidator ID =” rfvtxtNewSalary“ runat =” server“文本=” *“ToolTip =“输入薪水”
ControlToValidate =“ txtNewSalary”> </ asp :RequiredFieldValidator >
< asp :RegularExpressionValidator ID =“ revtxtNewSalary” runat =“ server”文本=“ *” ToolTip =“输入数字
值“ ControlToValidate =” txtNewSalary“ ValidationExpression =” ^ [0-9] + $“> </ asp :RegularExpressionValidator > </ FooterTemplate > </ asp :TemplateField > < asp :TemplateField > < HeaderTemplate >国家</ HeaderTemplate > <的ItemTemplate > < ASP :标签 ID = “原产国” RUNAT = “服务器”文本=”<%#
Bind(“ country”) %> '> </ asp :标签>
</ ItemTemplate > < EditItemTemplate > < asp :TextBox ID =“ txtCountry” runat =“ server” Text =' <%#Bind(“ country”) % > ' MaxLength =“ 20”> </ asp :文本框> < asp :RequiredFieldValidator ID =“ rfvtxtCountry” runat =“服务器”文字=“ *” ToolTip =“ Enter
国家” ControlToValidate =“ txtCountry”> </ asp :RequiredFieldValidator > </ EditItemTemplate > < FooterTemplate > < asp :TextBox ID =“ txtNewCountry” runat =“ server” MaxLength =“ 20”> </ asp :TextBox > < asp :RequiredFieldValidator ID =“ rfvtxtNewCountry” runat =“服务器”文本=“ *” ToolTip =“ Enter
国”的ControlToValidate = “txtNewCountry”> </ ASP :使用RequiredFieldValidator > </ FooterTemplate > </ ASP :的TemplateField > < ASP :的TemplateField > < HeaderTemplate中>市</ HeaderTemplate中> < ItemTemplate中> < ASP :标签 ID = “lblCity” RUNAT =“服务器”文本=' <%#Bind(“ city” ) %> '> </ asp
:标签>
</ ItemTemplate > < EditItemTemplate > < asp :TextBox ID =“ txtCity” runat =“服务器” Text =' <%#Bind(“ city”) %> ' MaxLength =“ 20”> </ asp :TextBox > < asp :RequiredFieldValidator ID =“ rfvtxtCity” runat =“服务器”文本=“ *” ToolTip =“输入城市”ControlToValidate =“ txtCity”> </ asp :
RequiredFieldValidator >
</ EditItemTemplate > < FooterTemplate > < asp :TextBox ID =“ txtNewCity” runat =“ server” MaxLength =“ 20”> </ asp :TextBox > < asp :RequiredFieldValidator ID =“ rfvtxtNewCity” runat =“ server”文本=“ *” ToolTip =“输入城市” ControlToValidate =“ txtNewCity”> </ asp :RequiredFieldValidator > </ FooterTemplate >
</ ASP :的TemplateField >
< ASP :的TemplateField > < HeaderTemplate中>照片</ HeaderTemplate中> < ItemTemplate中> < ASP :图像 ID = “imgPhoto”宽度= “100px的”高度= “100px的” RUNAT = “服务器”文本=“照片“ ImageUrl =' <%#Bind(” photopath“) %> ' /> </ ItemTemplate > < EditItemTemplate
>
< ASP :文件上传 ID = “fuPhoto” RUNAT = “服务器”工具提示= “选择雇员照片”/> < ASP :的RegularExpressionValidator ID = “revfuPhoto” RUNAT = “服务器”文本= “*”工具提示=“图像甲
仅“ ControlToValidate =“ fuPhoto” ValidationExpression =“ [a-zA-Z0_9]。* \ b(.jpeg | .JPEG | .jpg | .JPG | .jpe | .JPE | .png | .PNG | .mpp |。 MPP | .gif | .GIF)\ b“> </ asp :RegularExpressionValidator > </ EditItemTemplate > < FooterTemplate > < asp :FileUpload ID =” fuNewPhoto“ runat =” server“ ToolTip =” select雇员照片“ /> < asp :RequiredFieldValidator ID =“ rfvfuNewPhoto” runat =“服务器”ErrorMessage =“ *”工具提示
=“选择照片” ControlToValidate =“ fuNewPhoto”> </ asp :RequiredFieldValidator > < asp :RegularExpressionValidator ID =“ revfuNewPhoto” runat =“服务器”文本=“ *” ToolTip =“图像格式
仅“ ControlToValidate =“ fuNewPhoto” ValidationExpression =“ [a-zA-Z0_9]。* \ b(.jpeg | .JPEG | .jpg | .JPG | .jpe | .JPE | .png | .PNG | .mpp |。 MPP | .gif | .GIF)\ b“> </ asp :RegularExpressionValidator > </ FooterTemplate > </ asp :TemplateField > < asp :TemplateField > < HeaderTemplate >操作</ HeaderTemplate > < ItemTemplate > < asp :按钮 ID = “ btnEdit”Runat =“服务器”
CommandName =“编辑”文本=“编辑” /> < asp :按钮 ID =“ btnDelete” runat =“服务器” CommandName =“删除”文本=“ Delete” CausesValidation =“ true” OnClientClick =“返回确认('您是确定吗?')“ /> </ ItemTemplate > < EditItemTemplate > < asp :按钮 ID =” btnUpdate“ runat =”服务器“ CommandName =”更新“文字=“更新” /> < asp
:按钮 ID =“ btnCancel” runat =“服务器” CommandName =“取消” Text =“ Cancel” CausesValidation =“ false” /> </ EditItemTemplate > < FooterTemplate > < asp :按钮 ID =“ btnNewInsert” runat =“ server”文本= “插入”的OnClick = “InsertNewRecord”/> < ASP :按钮 ID = “btnNewCancel” RUNAT = “服务器”文字=“取消” OnClick =“ AddNewCancel”
的CausesValidation = “假” /> </ FooterTemplate > </ ASP :的TemplateField > </列> < EmptyDataTemplate > 无可用的记录 </ EmptyDataTemplate > </ ASP :GridView的> < BR /> < ASP :按钮 ID = “btnAdd” runat =“服务器”文本=“添加新
记录“ OnClick =” AddNewRecord“ /> </ div >
第4步: -内创建一个类 的 App_Code文件夹中。
在这里,我给了这个名为 GlobalClass的类, 并编写了以下代码行。
使用 System.Data;
使用 System.Data.SqlClient;
公共类GlobalClass {公共静态SqlDataAdapter adap; 公共静态数据表 dt; //在更新记录公共静态字符串 imgEditPath之前存储的图像路径;}
步骤5:-创建一个名为Images的文件夹,我们在其中存储了员工的照片,如下图所示。
使用C#在ASP.Net中的GridView中插入,删除,更新
步骤6:-在“中写下以下代码行。与“.aspx”页面相关的“ cs”页面 (例如,如果.aspx 页面名称为default.aspx, 则.cs 文件为default.aspx.cs)。
使用 系统;
使用 System.Data;
使用 System.Data.SqlClient;
使用 System.Configuration;
使用 System.Web.UI.WebControls;
使用 System.IO;
公共局部类_Default :System.Web.UI。页面{受保护的void Page_Load(对象 发送者, EventArgs e) {如果 (!IsPostBack) { //调用FillGridView方法 FillGridView(); } } /// <摘要> ///
将记录填充到GridView
//// </ summary> public void FillGridView() {试试 { string cnString = ConfigurationManager .ConnectionStrings [ “ dbconnection” ] .ConnectionString; SqlConnection con = 新的SqlConnection (cnString); GlobalClass .adap = 新的SqlDataAdapter (“ select * from gridview” ,con); SqlCommandBuilder bui = 新的SqlCommandBuilder (GlobalClass .adap); GlobalClass .dt = 新
DataTable ();
GlobalClass .adap.Fill(GlobalClass .dt); GridView1.DataSource
= GlobalClass .dt;
GridView1.DataBind();
}
catch { Response.Write(“ <script> alert('连接字符串
错误...')</ script>“ );
}
}
/// <summary> /// 编辑记录/// </ summary> /// <param
name =“ sender”> </ param>
/// <param
name =“ e”> </ param>
受保护的void editRecord(object sender, GridViewEditEventArgs e) { //获取图像路径以在之后删除旧图像
更新记录
Image imgEditPhoto = GridView1.Rows [e.NewEditIndex] .FindControl(“ imgPhoto” ) 作为Image ; GlobalClass .imgEditPath = imgEditPhoto.ImageUrl; //获取用于编辑记录 GridView1.EditIndex的当前行索引
= e.NewEditIndex;
FillGridView();
}
/// <summary> /// 取消操作(例如,编辑)/// </ summary> /// <param
name =“ sender”> </ param>
/// <param
name =“ e”> </ param>
受保护的void cancelRecord(对象 发送者, GridViewCancelEditEventArgs e) { GridView1.EditIndex
= -1;
FillGridView();
}
/// <summary> /// 如果在表中找不到记录,则向DataTable添加新行//// </ summary> /// <param
name =“ sender”> </ param>
/// <param
name =“ e”> </ param>
受保护的void AddNewRecord(对象 发送者, EventArgs e) {尝试 {如果 (GlobalClass .dt.Rows.Count> 0) { GridView1.EditIndex
= -1;
GridView1.ShowFooter
= true ;
FillGridView();
}
else { GridView1.ShowFooter
= true ;
DataRow dr = GlobalClass .dt.NewRow(); dr [ “ name” ] = “ 0” ; dr [ “ age” ] = 0;
dr [ “ salary” ] = 0; dr [ “ country” ] = “ 0” ; dr [ “ city” ] = “ 0” ; dr [ “ photopath” ] = “ 0” ; GlobalClass .dt.Rows.Add(dr); GridView1.DataSource
= GlobalClass .dt;
GridView1.DataBind();
GridView1.Rows [0]。可见
= 假;
}
}
catch { Response.Write(“ <script> alert('未在行中添加行
DataTable ...')</ script>“ );
}
}
/// <summary> /// 取消新添加的记录/// </ summary> /// <param
name =“ sender”> </ param>
/// <param
name =“ e”> </ param>
受保护的void AddNewCancel(object sender, EventArgs e) { GridView1.ShowFooter
= 假;
FillGridView();
}
/// <summary> /// 插入新记录/// </ summary> /// <param
name =“ sender”> </ param>
/// <param
name =“ e”> </ param>
受保护的void InsertNewRecord(object sender, EventArgs e) {试试 { string strName = GlobalClass .dt.Rows [0] [ “ name” ] .ToString(); 如果 (strName == “ 0” ) { GlobalClass .dt.Rows [0] .Delete(); GlobalClass .adap.Update(GlobalClass .dt); } TextBox txtName = GridView1.FooterRow.FindControl(“ txtNewName” ) 作为TextBox ;文本框
txtAge = GridView1.FooterRow.FindControl(“ txtNewAge” ) 作为TextBox ;TextBox txtSalary = GridView1.FooterRow.FindControl(“ txtNewSalary” ) 作为TextBox ;TextBox txtCountry = GridView1.FooterRow.FindControl(“ txtNewCountry” ) 作为TextBox ;TextBox txtCity = GridView1.FooterRow.FindControl(“ txtNewCity” ) 作为TextBox ;FileUpload fuPhoto = GridView1.FooterRow.FindControl(“ fuNewPhoto” ) 作为FileUpload ;引导
FileName = Guid .NewGuid();
fuPhoto.SaveAs(Server.MapPath(“〜/ Images /” + FileName + “ .png” ));
DataRow dr = GlobalClass .dt.NewRow(); dr [ “ name” ] = txtName.Text.Trim(); dr [ “ age” ] = txtAge.Text.Trim(); dr [ “ salary” ] = txtSalary.Text.Trim(); dr [ “ country” ] = txtCountry.Text.Trim(); dr [ “ city” ] = txtCity.Text.Trim(); dr [ “ photopath” ] = “
“ .png” ;
GlobalClass .dt.Rows.Add(dr); GlobalClass .adap.Update(GlobalClass .dt); GridView1.ShowFooter
= 假;
FillGridView();
}
catch { Response.Write(“ <script> alert('不记录
添加...')</ script>“ );
}
} /// <summary> /// 更新记录/// </ summary> /// <param
name =“ sender”> </ param>
/// <param
name =“ e”> </ param>
受保护的void updateRecord(对象 发送者, GridViewUpdateEventArgs e) {试试 { TextBox txtName = GridView1.Rows [e.RowIndex] .FindControl(“ txtName” ) 作为TextBox ;TextBox txtAge = GridView1.Rows [e.RowIndex] .FindControl(“ txtAge” ) 作为TextBox ;TextBox txtSalary = GridView1.Rows [e.RowIndex] .FindControl(“ txtSalary” ) 作为TextBox ;TextBox txtCountry = GridView1.Rows [e.RowIndex] .FindControl(
“ txtCountry” ) 作为TextBox ;TextBox txtCity = GridView1.Rows [e.RowIndex] .FindControl(“ txtCity” ) 作为TextBox ;FileUpload fuPhoto = GridView1.Rows [e.RowIndex] .FindControl(“ fuPhoto” ) 作为FileUpload ; Guid FileName = Guid .NewGuid(); 如果 (fuPhoto.FileName!= “” ) { fuPhoto.SaveAs(Server.MapPath(“〜/ Images /” + FileName + “ .png” )); GlobalClass .dt.Rows [GridView1.Rows [e.RowIndex]。
“ photopath” ] = “〜/ Images /” + FileName + “ .png” ;
文件.Delete(Server.MapPath(GlobalClass .imgEditPath)); } GlobalClass .dt.Rows [GridView1.Rows [e.RowIndex] .RowIndex] [ “ name” ] = txtName.Text.Trim(); GlobalClass .dt.Rows [GridView1.Rows [e.RowIndex] .RowIndex] [ “ age” ] = Convert .ToInt32(txtAge.Text.Trim()); GlobalClass .dt.Rows [GridView1.Rows [e.RowIndex] .RowIndex] [ “ salary” ] = 转换.ToInt32(txtSalary.Text.Trim()); GlobalClass .dt.Rows [GridView1.Rows [e.RowIndex]。
“ country” ] = txtCountry.Text.Trim();
GlobalClass .dt.Rows [GridView1.Rows [e.RowIndex] .RowIndex] [ “ city” ] = txtCity.Text.Trim(); GlobalClass .adap.Update(GlobalClass .dt); GridView1.EditIndex
= -1;
FillGridView();
}
catch { Response.Write(“ <script> alert('记录更新
失败...')</ script>“ );
}
}
/// <summary> /// 删除记录/// </ summary> /// <param
name =“ sender”> </ param>
/// <param
name =“ e”> </ param>
受保护的void RowDeleting(对象 发送者, GridViewDeleteEventArgs e) {尝试 { GlobalClass .dt.Rows [GridView1.Rows [e.RowIndex] .RowIndex] .Delete(); GlobalClass .adap.Update(GlobalClass .dt); //获取删除已删除图片的图片路径
将服务器文件夹中的
图像记录为Image imgPhoto = GridView1.Rows [e.RowIndex] .FindControl(“ imgPhoto” ) 作为Image ;文件.Delete(Server.MapPath(imgPhoto.ImageUrl)); FillGridView(); } catch { Response.Write(“ <script> alert('不记录
删除...')</ script>“ );
}
}
}
步骤7:- 现在,保存并构建您的应用程序并执行。您的应用程序输出显示如下。
使用C#在ASP.Net中的GridView中插入,删除,更新
这是您的应用程序的第一个屏幕。由于表中没有数据,因此它将替换消息“ No record available ”。
步骤8:- 要插入数据,请单击“添加新记录”按钮。现在填充数据。每个控件都有针对禁止的错误输入的验证。
使用C#在ASP.Net中的GridView中插入,删除,更新
填充数据后,您的GridView如下所示。 在这里,我插入了三个记录。
使用C#在ASP.Net中的GridView中插入,删除,更新
注意:-为每个新记录自动生成ID。
步骤9:-要更新记录,请单击按钮“编辑”并更改TextBox 数据,然后可以选择该员工的新照片。例如,以年龄 “ 28”代替“ 30”,以工资 “ 50000”代替“ 55000”,然后单击“更新”按钮。通过按钮“取消” 返回 上一级。
使用C#在ASP.Net中的GridView中插入,删除,更新
步骤10:- 要删除记录,请单击 “删除”按钮。 在删除记录之前,会弹出一条确认警报消息。
在这里,我删除了第3条 记录(例如 Andrew Daniel)。删除记录后,您的 GridView 如下所示。