官术网_书友最值得收藏!

2.3 最基本的數(shù)據(jù)綁定

下面使用GridView綁定最基本的一個數(shù)據(jù)庫中的一個表,數(shù)據(jù)庫采用章立民先生的北風(fēng)貿(mào)易數(shù)據(jù)庫,該數(shù)據(jù)庫出現(xiàn)于他的多部著作,是一個非常好的演示數(shù)據(jù)庫。

后臺代碼如下:

        using System;
        using System.Collections;
        using System.Configuration;
        using System.Data;
        using System.Linq;
        using System.Web;
        using System.Web.Security;
        using System.Web.UI;
        using System.Web.UI.HtmlControls;
        using System.Web.UI.WebControls;
        using System.Web.UI.WebControls.WebParts;
        using System.Xml.Linq;
        using System.Data.SqlClient;
        namespace WebApplication.GridView
        {
        publicpartialclassReportPage : System.Web.UI.Page
            {
        SqlConnection sqlcon;
        string strCon=ConfigurationManager.ConnectionStrings[ "SQLCONN" ].ToString();
        protectedvoid Page_Load(object sender, EventArgs e)
              {
        if (!IsPostBack)
                    {
                        bind();
                    }
              }
        //綁定數(shù)據(jù)
        publicvoid bind()
              {
        string sqlstr="select top 10 員工編號,身份證號碼,姓名,性別,地址 from 章立民工作室";
                    sqlcon=newSqlConnection(strCon);
        SqlDataAdapter myda=newSqlDataAdapter(sqlstr, sqlcon);
        DataSet myds=newDataSet();
                    sqlcon.Open();
                    myda.Fill(myds, "table");
                    GridView1.DataSource=myds;
                    GridView1.DataBind();
                    sqlcon.Close();
              }
            }
        }

前臺代碼如下:

        ……
        <formid="form1"runat="server">
        <div>
        <asp:GridViewID="GridView1"runat="server">
        </asp:GridView>
        </div>
        </form>

說明:數(shù)據(jù)庫連接字符串“SQLCONN”寫在webconfig中,這里為了演示就沒有分多層,那樣不便于說明。初學(xué)者不要忘記引入名稱空間“using System.Data.SqlClient;”關(guān)于數(shù)據(jù)綁定不在這里多說明。

主站蜘蛛池模板: 黄山市| 玉龙| 沁水县| 鄂伦春自治旗| 长兴县| 霍州市| 容城县| 江达县| 富阳市| 阆中市| 方城县| 芮城县| 修武县| 保康县| 马公市| 邢台县| 庄河市| 肃南| 阿拉尔市| 尼木县| 巫溪县| 辉县市| 台湾省| 宜黄县| 榆社县| 灵台县| 开原市| 晋宁县| 中宁县| 喀喇沁旗| 江永县| 宜川县| 禄丰县| 新民市| 承德市| 江津市| 建德市| 札达县| 怀仁县| 宝山区| 黄冈市|