利用ViewState和DataTable动态录入数据的例子

原创 2011年08月11日 13:25:48
本例子是论坛上的网友提问的问题,由于经常会有人用到,就贴在这里,供初学者练习。
<%@ Page Language="C#" EnableViewState="true" %>

<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
  private DataTable stoveTable = null;
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!Page.IsPostBack)
    {
      //创建 EmptyDataTemplate
      this.GridView_list.DataBind();
    }
  }

  protected void GridView_list_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      String usage = DataBinder.Eval(e.Row.DataItem, "usage").ToString();
      String steelKind = DataBinder.Eval(e.Row.DataItem, "steelKind").ToString();
      String castingTon = DataBinder.Eval(e.Row.DataItem, "castingTon").ToString();
      DropDownList x1 = e.Row.FindControl("x1") as DropDownList;
      DropDownList x2 = e.Row.FindControl("x2") as DropDownList;
      TextBox x3 = e.Row.FindControl("x3") as TextBox;
      x3.Text = castingTon;
      ListItem xx1 = x1.Items.FindByValue(usage);
      if (xx1 != null) xx1.Selected = true;
      ListItem xx2 = x2.Items.FindByValue(steelKind);
      if (xx2 != null) xx2.Selected = true;
    }
  }

  protected void LinkButton1_Click(object sender, EventArgs e)
  {
    DropDownList x1, x2;
    TextBox x3;
    if (GridView_list.Rows.Count == 0)
    {
      x1 = GridView_list.Controls[0].Controls[0].FindControl("x1") as DropDownList;
      x2 = GridView_list.Controls[0].Controls[0].FindControl("x2") as DropDownList;
      x3 = GridView_list.Controls[0].Controls[0].FindControl("x3") as TextBox;
    }
    else
    {
      GridViewRow r = GridView_list.FooterRow;
      x1 = r.FindControl("x1") as DropDownList;
      x2 = r.FindControl("x2") as DropDownList;
      x3 = r.FindControl("x3") as TextBox;
    }
    if (ViewState["dt"] == null)
    {
      stoveTable = new DataTable();
      stoveTable.Columns.Add("usage", typeof(String));
      stoveTable.Columns.Add("steelKind", typeof(String));
      stoveTable.Columns.Add("castingTon", typeof(String));
    }
    else
    {
      stoveTable = (DataTable)ViewState["dt"];
    }
    DataRow newRow = stoveTable.NewRow();
    newRow["usage"] = x1.SelectedValue;
    newRow["steelKind"] = x2.SelectedValue;
    newRow["castingTon"] = x3.Text;
    stoveTable.Rows.Add(newRow);

    ViewState["dt"] = stoveTable;
    this.GridView_list.DataSource = stoveTable;
    this.GridView_list.DataBind();

  }
  protected void LinkButton2_Click(object sender, EventArgs e)
  {
    if (ViewState["dt"] == null)
    {
      return;
    }
    stoveTable = (DataTable)ViewState["dt"];
    if (stoveTable.Rows.Count < 1) return;
    stoveTable.Rows.RemoveAt(stoveTable.Rows.Count - 1);
    ViewState["dt"] = stoveTable;
    this.GridView_list.DataSource = stoveTable;
    this.GridView_list.DataBind();
  }

  protected void x1_SelectedIndexChanged(object sender, EventArgs e)
  {
    DropDownList x1 = sender as DropDownList;
    GridViewRow r = x1.Parent.Parent as GridViewRow;
    if (ViewState["dt"] == null)
    {
      Response.Write("Error");
      return;
    }
    stoveTable = (DataTable)ViewState["dt"];
    stoveTable.Rows[r.RowIndex]["usage"] = x1.SelectedValue;
    ViewState["dt"] = stoveTable;
    this.GridView_list.DataSource = stoveTable;
    this.GridView_list.DataBind();
  }

  protected void x2_SelectedIndexChanged(object sender, EventArgs e)
  {
    DropDownList x2 = sender as DropDownList;
    GridViewRow r = x2.Parent.Parent as GridViewRow;
    if (ViewState["dt"] == null)
    {
      Response.Write("Error");
      return;
    }
    stoveTable = (DataTable)ViewState["dt"];
    stoveTable.Rows[r.RowIndex]["steelKind"] = x2.SelectedValue;
    ViewState["dt"] = stoveTable;
    this.GridView_list.DataSource = stoveTable;
    this.GridView_list.DataBind();
  }

  protected void x3_TextChanged(object sender, EventArgs e)
  {

    TextBox x3 = sender as TextBox;
    GridViewRow r = x3.Parent.Parent as GridViewRow;
    if (ViewState["dt"] == null)
    {
      Response.Write("Error");
      return;
    }
    stoveTable = (DataTable)ViewState["dt"];
    stoveTable.Rows[r.RowIndex]["castingTon"] = x3.Text;
    ViewState["dt"] = stoveTable;
    this.GridView_list.DataSource = stoveTable;
    this.GridView_list.DataBind();
  }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <asp:GridView ID="GridView_list" runat="server" ShowFooter="true" AutoGenerateColumns="false"
    OnRowDataBound="GridView_list_RowDataBound">
    <EmptyDataTemplate>
      <table style="border-collapse: collapse; width: 100%" cellspacing="0" rules="all"
        border="1">
        <tr>
          <th scope="col">
            选择1
          </th>
          <th scope="col">
            选择2
          </th>
          <th scope="col">
            输入文字
          </th>
        </tr>
        <tr><td>
          <asp:DropDownList ID="x1" runat="server">
            <asp:ListItem>L0</asp:ListItem>
            <asp:ListItem>L1</asp:ListItem>
            <asp:ListItem>L2</asp:ListItem>
            <asp:ListItem>L3</asp:ListItem>
          </asp:DropDownList>
        </td><td>
          <asp:DropDownList ID="x2" runat="server">
            <asp:ListItem>10#</asp:ListItem>
            <asp:ListItem>20#</asp:ListItem>
            <asp:ListItem>30#</asp:ListItem>
            <asp:ListItem>40#</asp:ListItem>
          </asp:DropDownList>
        </td><td>
          <asp:TextBox ID="x3" runat="server"></asp:TextBox>
        </td></tr>
      </table>
    </EmptyDataTemplate>
    <Columns>
      <asp:TemplateField HeaderText="选择1">
        <ItemTemplate>
          <asp:DropDownList ID="x1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="x1_SelectedIndexChanged">
            <asp:ListItem>L0</asp:ListItem>
            <asp:ListItem>L1</asp:ListItem>
            <asp:ListItem>L2</asp:ListItem>
            <asp:ListItem>L3</asp:ListItem>
          </asp:DropDownList>
        </ItemTemplate>
        <FooterTemplate>
          <asp:DropDownList ID="x1" runat="server">
            <asp:ListItem>L0</asp:ListItem>
            <asp:ListItem>L1</asp:ListItem>
            <asp:ListItem>L2</asp:ListItem>
            <asp:ListItem>L3</asp:ListItem>
          </asp:DropDownList>
        </FooterTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="选择2">
        <ItemTemplate>
          <asp:DropDownList ID="x2" runat="server" AutoPostBack="true" OnSelectedIndexChanged="x2_SelectedIndexChanged">
            <asp:ListItem>10#</asp:ListItem>
            <asp:ListItem>20#</asp:ListItem>
            <asp:ListItem>30#</asp:ListItem>
            <asp:ListItem>40#</asp:ListItem>
          </asp:DropDownList>
        </ItemTemplate>
        <FooterTemplate>
          <asp:DropDownList ID="x2" runat="server">
            <asp:ListItem>10#</asp:ListItem>
            <asp:ListItem>20#</asp:ListItem>
            <asp:ListItem>30#</asp:ListItem>
            <asp:ListItem>40#</asp:ListItem>
          </asp:DropDownList>
        </FooterTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="输入文字">
        <ItemTemplate>
          <asp:TextBox ID="x3" runat="server" AutoPostBack="true" OnTextChanged="x3_TextChanged"></asp:TextBox>
        </ItemTemplate>
        <FooterTemplate>
          <asp:TextBox ID="x3" runat="server"></asp:TextBox>
        </FooterTemplate>
      </asp:TemplateField>
    </Columns>
  </asp:GridView>
  <asp:LinkButton ID="LinkButton1" runat="server" Text="添加内容" OnClick="LinkButton1_Click"></asp:LinkButton>
  <asp:LinkButton ID="LinkButton2" runat="server" Text="删除内容" OnClick="LinkButton2_Click"></asp:LinkButton>
  </form>
</body>
</html>

下面采用另外一种方法,

<%@ Page Language="C#" AutoEventWireup="true" EnableViewState="true" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
  private DataTable dataTable = null;
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!Page.IsPostBack)
    {
      this.Bind(true);
    }
  }

  private DataTable GetDataTable()
  {
    if (ViewState["dt"] == null)
    {
      dataTable = new DataTable();
      dataTable.Columns.Add("usage", typeof(String));
      dataTable.Columns.Add("steelKind", typeof(String));
      dataTable.Columns.Add("castingTon", typeof(String));
      return dataTable;
    }
    else
    {
      return ViewState["dt"] as DataTable;
    }
  }

  private void Bind(bool AddBlankRow)
  {
    dataTable = GetDataTable();
    if (AddBlankRow) dataTable.Rows.Add(dataTable.NewRow());
    this.GridView1.DataSource = dataTable;
    this.GridView1.DataBind();
  }
  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      DropDownList x1 = e.Row.FindControl("x1") as DropDownList;
      DropDownList x2 = e.Row.FindControl("x2") as DropDownList;
      TextBox x3 = e.Row.FindControl("x3") as TextBox;

      String usage = DataBinder.Eval(e.Row.DataItem, "usage").ToString();
      String steelKind = DataBinder.Eval(e.Row.DataItem, "steelKind").ToString();
      String castingTon = DataBinder.Eval(e.Row.DataItem, "castingTon").ToString();

      x3.Text = castingTon;
      ListItem xx1 = x1.Items.FindByValue(usage);
      if (xx1 != null) xx1.Selected = true;
      ListItem xx2 = x2.Items.FindByValue(steelKind);
      if (xx2 != null) xx2.Selected = true;
    }
  }

  protected void LinkButton1_Click(object sender, EventArgs e)
  {
    //总是取最后的一行
    GridViewRow row = GridView1.Rows[GridView1.Rows.Count - 1];
    DropDownList x1 = row.FindControl("x1") as DropDownList;
    DropDownList x2 = row.FindControl("x2") as DropDownList;
    TextBox x3 = row.FindControl("x3") as TextBox;

    dataTable = this.GetDataTable();
    DataRow newRow = dataTable.NewRow();
    if (dataTable.Rows.Count > 0)
    {
      newRow = dataTable.Rows[dataTable.Rows.Count - 1];
    }

    newRow["usage"] = x1.SelectedValue;
    newRow["steelKind"] = x2.SelectedValue;
    newRow["castingTon"] = x3.Text;
    if (dataTable.Rows.Count == 0)
    {
      dataTable.Rows.Add(newRow);
    }

    ViewState["dt"] = dataTable;
    this.Bind(true);

  }
  protected void LinkButton2_Click(object sender, EventArgs e)
  {
    dataTable = this.GetDataTable();
    if (dataTable.Rows.Count < 1) return;
    dataTable.Rows.RemoveAt(dataTable.Rows.Count - 1);
    ViewState["dt"] = dataTable;
    this.Bind(false);
  }

  protected void x1_SelectedIndexChanged(object sender, EventArgs e)
  {
    DropDownList x1 = sender as DropDownList;
    GridViewRow r = x1.Parent.Parent as GridViewRow;
    dataTable = this.GetDataTable();
    dataTable.Rows[r.RowIndex]["usage"] = x1.SelectedValue;
    ViewState["dt"] = dataTable;
    this.Bind(false);
  }

  protected void x2_SelectedIndexChanged(object sender, EventArgs e)
  {
    DropDownList x2 = sender as DropDownList;
    GridViewRow r = x2.Parent.Parent as GridViewRow;
    dataTable = this.GetDataTable();
    dataTable.Rows[r.RowIndex]["steelKind"] = x2.SelectedValue;
    ViewState["dt"] = dataTable;
    this.Bind(false);
  }

  protected void x3_TextChanged(object sender, EventArgs e)
  {
    TextBox x3 = sender as TextBox;
    GridViewRow r = x3.Parent.Parent as GridViewRow;
    dataTable = this.GetDataTable();
    dataTable.Rows[r.RowIndex]["castingTon"] = x3.Text;
    ViewState["dt"] = dataTable;
    this.Bind(false);
  }

  protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      if (e.Row.RowIndex < this.GetDataTable().Rows.Count - 1)
      {
        DropDownList x1 = e.Row.FindControl("x1") as DropDownList;
        DropDownList x2 = e.Row.FindControl("x2") as DropDownList;
        TextBox x3 = e.Row.FindControl("x3") as TextBox;
        x1.AutoPostBack = x2.AutoPostBack = x3.AutoPostBack = true;
        x1.SelectedIndexChanged += new EventHandler(x1_SelectedIndexChanged);
        x2.SelectedIndexChanged += new EventHandler(x2_SelectedIndexChanged);
        x3.TextChanged += new EventHandler(x3_TextChanged);
      }
    }
  }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound"
    OnRowCreated="GridView1_RowCreated">
    <Columns>
      <asp:TemplateField HeaderText="选择1">
        <ItemTemplate>
          <asp:DropDownList ID="x1" runat="server">
            <asp:ListItem>L0</asp:ListItem>
            <asp:ListItem>L1</asp:ListItem>
            <asp:ListItem>L2</asp:ListItem>
            <asp:ListItem>L3</asp:ListItem>
          </asp:DropDownList>
        </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="选择2">
        <ItemTemplate>
          <asp:DropDownList ID="x2" runat="server">
            <asp:ListItem>10#</asp:ListItem>
            <asp:ListItem>20#</asp:ListItem>
            <asp:ListItem>30#</asp:ListItem>
            <asp:ListItem>40#</asp:ListItem>
          </asp:DropDownList>
        </ItemTemplate>
      </asp:TemplateField>
      <asp:TemplateField HeaderText="输入文字">
        <ItemTemplate>
          <asp:TextBox ID="x3" runat="server"></asp:TextBox>
        </ItemTemplate>
      </asp:TemplateField>
    </Columns>
  </asp:GridView>
  <asp:LinkButton ID="LinkButton1" runat="server" Text="添加内容" OnClick="LinkButton1_Click"></asp:LinkButton>
  <asp:LinkButton ID="LinkButton2" runat="server" Text="删除内容" OnClick="LinkButton2_Click"></asp:LinkButton>
  </form>
</body>
</html>


相关文章推荐

利用GridView显示主细表并一次编辑明细表所有数据的例子

全部代码如下: ASPX:@ Page Language="C#" ValidateRequest="false" AutoEventWireup="true" EnableViewState="fa...

利用ViewState和DataTable动态录入数据

private DataTable stoveTable = null; protected void Page_Loa

怎样改变多行文本框滚动条的颜色??

怎样改变多行文本框滚动条的颜色??作者:http://lucky.myrice.comE-mail:amxh@21cn.com  在IE5.5中,你可以设定或者改变滚动条的颜色、三角箭头的颜色、滚动条...

关于Jquery datatable动态加载数据心得

在使用Jquery Datatable控件对列表页面进行分页,一直搞不清楚传入后台的值里面怎么获取pageNumber的值,后面一直监控aoData的json字段,终于发现,iDisplayStart...

DataTable纵向记录转换成横向列显示,动态新增列及填充数据

DataTable dt = Maticsoft.DBUtility.DbHelperOra.Query(QuerySql).Tables[0]; #region 创建新的DataTable ...

dataTable 根据不同行数据动态显示行操作

mReader:function(data,type,full)其中的full就是这一列的所有信息,试验了一下,的却访问隐藏的那一列,那么通过这种变相的方法就可以访问隐藏的数据了...

简单高级搜索页面的简单实现,包括数据控件循环嵌套,DataTable动态生成数据添加等

public partial class _Default : System.Web.UI.Page { DBHelper db = new DBHelper(); ...

关于jquery.datatable插件从数据库动态读取数据-动态分页

在上篇随笔中所提到的数据插入方法,是将所有数据一次性读出并插入表格,只能针对数据量小的操作。 本篇随笔记录的是datatable插件服务器端分页读取数据的方法。 一、分页 分页的基本...

关于jquery.datatable插件从数据库动态读取数据-动态分页

在上篇随笔中所提到的数据插入方法,是将所有数据一次性读出并插入表格,只能针对数据量小的操作。 本篇随笔记录的是datatable插件服务器端分页读取数据的方法。 一、分页 分页的基本...
  • lisky119
  • lisky119
  • 2014年05月15日 12:42
  • 25465
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:利用ViewState和DataTable动态录入数据的例子
举报原因:
原因补充:

(最多只允许输入30个字)