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

来源:互联网 发布:cf辅助瞄准软件 编辑:程序博客网 时间:2024/05/20 08:44

这个栗子的分析请回头看前面那章节的分析:关于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();
    }
}