注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

_

_

 
 
 

日志

 
 

GridView 实现插入数据  

2014-09-17 02:20:50|  分类: 默认分类 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
GridView 实现插入数据

2011-03-02 14:53:20|? 分类: ASP |? 标签:gridview实现插入 gridview实现插入数据 gridview插入数据 gridview插入 asp.net |举报 |字号大中小 订阅

看了? 清清月儿? 的 GridView 72 般绝技 觉得 GridView 真的是非常的强大,网上找了很多些GridView插入数据的日志,都没有找到自己想要的,

如果 GridView 能插入数据了,那可真是如虎添翼啊~~呵呵

在 MSDN 上看到 GridView 有个 CreateRow 的受保护的方法:

protected virtual GridViewRow CreateRow(
int rowIndex,
int dataSourceIndex,
DataControlRowType rowType,
DataControlRowState rowState
)

想到个 idea ,就是自己开发个控件继承自 GridView ,然后公开一个 CreateNewRow 方法来调用 GridView.CreateRow 来创建新数据行,并设置新行的状态为编辑的,后来实践了一番,还是没弄懂 GridVIew.CreateRow 方法的原理,但是遇到个更好的方法来实现:

就是用到 GridView 的 EmptyDataTemplate 模板(from msdn : 获取或设置在 GridView 控件绑定到不包含任何记录的数据源时所呈现的空数据行的用户定义内容。)

简单概括就是:一个"添加"按钮把gridview的 DataSource 设置成 null,调用 gridview.DataBind() 方法,就会跳至 EmptyDataTemplate , 我们可以在 EmptyDataTemplate 模板中添加 DetailsView (并把DetailsView 的 DefaultMode 设置成 "Insert" )来实现添加插入的功能

现在应该明白 GridView 插入数据的方法了吧

如果还未懂就复制代码浏览效果吧...

public partial class _Default : System.Web.UI.Page
{
??? protected void Page_Load(object sender, EventArgs e)
??? {
??????? if (!IsPostBack)
??????? {
??????????? Bind();??
??????? }
??? }

??? /// <summary>
??? /// 绑定数据到 GridView
??? /// </summary>
??? void Bind()
??? {
??????? DataSet ds = GetData();
??????? var data = from p in ds.Tables[0].AsEnumerable()
?????????????????? join c in ds.Tables[1].AsEnumerable() on p.Field<int>("CatalogID") equals c.Field<int>("CatalogID")
?????????????????? select new
?????????????????? {
?????????????????????? ProductID = p.Field<Guid>("ProductID"),
?????????????????????? Name = p.Field<string>("Name"),
?????????????????????? Catalog = c.Field<string>("Name"),
?????????????????????? Description = p.Field<string>("Description")
?????????????????? };
??????? gvData.DataSource = data;
??????? gvData.DataBind();
??? }

??? /// <summary>
??? /// 处理模式更改的事件
??? /// </summary>
??? /// <param name="sender"></param>
??? /// <param name="e"></param>
??? protected void dvData_ModeChanging(object sender, DetailsViewModeEventArgs e)
??? {
??????? if (e.CancelingEdit)
??????? {
??????????? if (e.NewMode== DetailsViewMode.Insert)
??????????? {
??????????????? Bind();
??????????? }
??????? }
??? }
??? /// <summary>
??? /// insert
??? /// </summary>
??? /// <param name="sender"></param>
??? /// <param name="e"></param>
??? protected void dvData_ItemInserting(object sender, DetailsViewInsertEventArgs e)
??? {
??????? // 页面逻辑验证通过后获取数据
??????? DetailsView dv = sender as DetailsView;
??????? TextBox txtName = dv.FindControl("txtName") as TextBox;
??????? DropDownList ddlCatalog = dv.FindControl("ddlCatalog") as DropDownList;
??????? TextBox txtDes = dv.FindControl("txtDescription") as TextBox;
??????? if (null != txtName && null != txtDes && null != ddlCatalog)
??????? {
??????????? string name = txtName.Text.Trim();
??????????? string catalogID = ddlCatalog.SelectedValue;
??????????? string description = txtDes.Text.Trim();
??????? }
??????? // 逻辑验证...
??????? // ...
??????? // 执行插入...
??? }

??? #region// 模拟数据

??? /// <summary>
??? /// 产品列表(模拟数据)
??? /// </summary>
??? /// <returns></returns>
??? DataTable ProductTable()
??? {
??????? DataTable tb = new DataTable();
??????? DataColumn col = new DataColumn("ProductID", typeof(Guid)) { Unique = true, AllowDBNull = false };
??????? tb.Columns.Add(col);
??????? tb.Columns .Add (new DataColumn ("Name",typeof(string )));
??????? tb.Columns.Add(new DataColumn("CatalogID", typeof(int)));
??????? tb.Columns.Add(new DataColumn("Description", typeof(string)));
??????? tb.PrimaryKey = new DataColumn[] { col };

??????? DataRow dr = tb.NewRow();
??????? dr[0] = Guid.NewGuid();
??????? dr[1] = "G450";//computer
??????? dr[2] = 1;
??????? dr[3] = "lenovo note pad";
??????? tb.Rows.Add(dr);

??????? dr = tb.NewRow();
??????? dr[0] = Guid.NewGuid();
??????? dr[1] = "TV";//electrical furniture
??????? dr[2] = 2;
??????? dr[3] = "SAMSUNG";
??????? tb.Rows.Add(dr);

??????? dr = tb.NewRow();
??????? dr[0] = Guid.NewGuid();
??????? dr[1] = "desk";//others
??????? dr[2] = 3;
??????? dr[3] = "none";
??????? tb.Rows.Add(dr);
??????? return tb;
??? }

??? /// <summary>
??? /// 产品类别(模拟数据)
??? /// </summary>
??? /// <returns></returns>
??? protected DataTable CatalogTable()
??? {
??????? DataTable tb = new DataTable();
??????? DataColumn col1 = new DataColumn("CatalogID", typeof(int)) { AllowDBNull = false, AutoIncrement = true, AutoIncrementSeed = 1, AutoIncrementStep = 1 };
??????? DataColumn col2 = new DataColumn("Name", typeof(string)) { Unique = true, AllowDBNull = false };
??????? tb.Columns.Add(col1);
??????? tb.Columns.Add(col2);
??????? tb.PrimaryKey = new DataColumn[] { col1 };

??????? DataRow dr = tb.NewRow();
??????? dr["Name"] = "computer";
??????? tb.Rows.Add(dr);

??????? dr = tb.NewRow();
??????? dr["name"] = "electrical furniture";
??????? tb.Rows.Add(dr);

??????? dr = tb.NewRow();
??????? dr["NAME"] = "others";
??????? tb.Rows.Add(dr);

??????? return tb;
??? }

??? /// <summary>
??? /// 获取要绑定的数据
??? /// </summary>
??? /// <returns></returns>
??? DataSet GetData()
??? {
??????? DataSet ds = new DataSet();
??????? DataTable _tbProduct = ProductTable();
??????? DataTable _tbCatalog = CatalogTable();
??????? ds.Tables.Add(_tbProduct);
??????? ds.Tables.Add(_tbCatalog);
??????? ForeignKeyConstraint fk = new ForeignKeyConstraint(_tbCatalog.Columns["CatalogID"], _tbProduct.Columns["CatalogID"]);
??????? _tbProduct.Constraints.Add(fk);
??????? return ds;
??? }

??? #endregion
??? /// <summary>
??? /// 处理用户单击"新增产品"按钮的事件,跳转到 EmptyDataTemplate 模板
??? /// </summary>
??? /// <param name="sender"></param>
??? /// <param name="e"></param>
??? protected void OnAddRecordClick(object sender, EventArgs e)
??? {
??????? gvData.DataSource = null;
??????? gvData.DataBind();
??? }
}

前台页面代码

源代码用到 Eval 方法须导入命名空间:<%@ Import Namespace="System.Data" %>

<form id="form1" runat="server">
??? <div style="text-align:center">
??????? <asp:GridView runat="server" ID="gvData" AutoGenerateColumns="false" Font-Size="Small">
??????????? <Columns >
??????????????? <asp:TemplateField HeaderText="产品编号 ">
??????????????????? <ItemTemplate>
??????????????????????? <span><%#Eval ("ProductID") %></span>
??????????????????? </ItemTemplate>
??????????????? </asp:TemplateField>
??????????????? <asp:TemplateField HeaderText="产品名称 ">
??????????????????? <ItemTemplate>
??????????????????????? <span><%#Eval ("Name") %></span>
??????????????????? </ItemTemplate>
??????????????? </asp:TemplateField>
??????????????? <asp:TemplateField HeaderText="产品类别 ">
??????????????????? <ItemTemplate>
??????????????????????? <span><%#Eval ("Catalog") %></span>
??????????????????? </ItemTemplate>
??????????????? </asp:TemplateField>
??????????????? <asp:TemplateField HeaderText="描述 ">
??????????????????? <ItemTemplate>
??????????????????????? <span><%#Eval ("Description") %></span>
??????????????????? </ItemTemplate>
??????????????? </asp:TemplateField>
??????????? </Columns>
??????????? <EmptyDataTemplate>
??????????????? <asp:DetailsView runat="server" ID="dvData" AutoGenerateRows="False"
??????????????????? DefaultMode="Insert" oniteminserting="dvData_ItemInserting"
??????????????????? onmodechanging="dvData_ModeChanging">
??????????????????? <Fields >
??????????????????????? <%--<asp:TemplateField HeaderText="产品编号">
??????????????????????????? <InsertItemTemplate >
??????????????????????????????? <asp:TextBox ID="txtId" runat="server"></asp:TextBox>
??????????????????????????? </InsertItemTemplate>
??????????????????????? </asp:TemplateField>--%>
??????????????????????? <asp:TemplateField HeaderText="产品名称">
??????????????????????????? <InsertItemTemplate >
??????????????????????????????? <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
??????????????????????????? </InsertItemTemplate>
??????????????????????? </asp:TemplateField>
??????????????????????? <asp:TemplateField HeaderText="类别">
??????????????????????????? <InsertItemTemplate >
??????????????????????????????? <asp:DropDownList runat="server" ID="ddlCatalog" DataSource='<%# CatalogTable() %>' DataValueField="CatalogID" DataTextField="Name" >
??????????????????????????????? </asp:DropDownList>
??????????????????????????? </InsertItemTemplate>
??????????????????????? </asp:TemplateField>
??????????????????????? <asp:TemplateField HeaderText="描述">
??????????????????????????? <InsertItemTemplate >
??????????????????????????????? <asp:TextBox ID="txtDescription" runat="server"></asp:TextBox>
??????????????????????????? </InsertItemTemplate>
??????????????????????? </asp:TemplateField>
??????????????????????? <asp:CommandField ShowInsertButton ="true" InsertText="录入" ShowCancelButton ="true"
??????????????????????????? CancelText="返回" />???????????????????????????
??????????????????? </Fields>
??????????????? </asp:DetailsView>
??????????? </EmptyDataTemplate>
??????? </asp:GridView><hr />
??????? <asp:Button ID="btnAdd" runat="server" Text="新增产品" Height="22px"
??????????? onclick="OnAddRecordClick" />
??? </div>
??? </form>

  评论这张
 
阅读(373)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017