将TextBox数据提交到GridView显示(DataTable的应用2)

这个栗子的分析请回头看前面那章节的分析:关于DataTable如何取值

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class DataSet_InsertData : System.Web.UI.Page
{
    private string strConn = "data source=localhost;initial catalog=Northwind;user id=sa;password=sa";
    SqlConnection Conn;
    SqlDataAdapter myDataAdapter;
    DataSet myDataSet;
    protected void Page_Load(object sender, EventArgs e)
    {
        Conn = new SqlConnection(strConn);
        string strSql = "SELECT * FROM Categories";
        myDataAdapter = new SqlDataAdapter(strSql, Conn);
        //创建CommandBuilder对象,该对象可以自动创建用于插入、删除及更新的SQL语句
        SqlCommandBuilder myCB = new SqlCommandBuilder(myDataAdapter);
        if (!IsPostBack)
        {
            //调用FillGridView()方法,用以显示数据
            FillGridView();
        }
    }
    private void FillGridView()
    {
        myDataSet = new DataSet();
        Conn.Open();
        myDataAdapter.Fill(myDataSet, "Categories");
        Conn.Close();
        myGridView.DataSource = myDataSet.Tables["Categories"];
        myGridView.DataBind();
    }
    protected void OK_Click(object sender, EventArgs e)
    {
        DataSet InsertDataSet = new DataSet();
        Conn.Open();
        myDataAdapter.Fill(InsertDataSet, "Categories");
        Conn.Close();
        //创建一个新行,准备添加新的数据
        DataRow insertRow = InsertDataSet.Tables["Categories"].NewRow();
        //指定新行中每一个字段的值
        insertRow["CategoryName"] = txtCategoryName.Text;
        insertRow["Description"] = txtDescription.Text;
        //将创建并填充数据的行insertRow添加到InsertDataSet中的Categories表格中
        InsertDataSet.Tables["Categories"].Rows.Add(insertRow);
        //使用DataAdapter对象的Update方法更新插入新行后的数据表Categories
        myDataAdapter.Update(InsertDataSet.Tables["Categories"]);
        txtCategoryName.Text = "";
        txtDescription.Text = "";
        //调用FillGridView()方法,重新显示插入新行后的数据信息
        FillGridView();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值