asp.net中數據綁定的寫法

using System;
using System.Data;
using System.Data.SqlClient;
……
namespace XXXX.xxxxxxx
{
 /// <summary>
 /// xxxxx 的摘要說明。
 /// </summary>
 public class xxxxx : System.Web.UI.Page
 {
  protected System.Data.DataRow dr;
  protected System.Data.SqlClient.SqlConnection conn;
  protected System.Data.SqlClient.SqlCommand myCmd,mysqlcmd;
  private void Page_Load(object sender, System.EventArgs e)
  {
   string connstr="data source=xxx.xxx.xxx.xxx;uid=xxxx;pwd=****;database=xxxx";;
   this.conn=new System.Data.SqlClient.SqlConnection(connstr);
  }
//使用SqlDataReader綁定數據
  private void XXXX_Bound()
  {
   conn.Open();
   sql="SELECT * from xxxx ";
    
   myCmd = conn.CreateCommand();
   myCmd.CommandText =sql;
   SqlDataReader sqr=myCmd.ExecuteReader();
   
   while(sqr.Read())
   {
    tb_xxxx.Text=sqr[0].ToString().Trim();
    ……
    
    for(int i=0; i<ddl_xxxx.Items.Count; i++)
    {
     if(ddl_xxxx.Items[i].Value.Trim() == sqr[8].ToString().Trim())
     {
      ddl_xxxx.SelectedIndex = i;
     }
    }

    ……
   }
   conn.Close();
  }
//使用DataTable存取數據後綁定
  private void DataGrid2_Bound()
  {
   conn.Open();
   SqlCommand myCommand= conn.CreateCommand();

   myCommand.CommandText="sp_xxxxxx";
   myCommand.CommandType=CommandType.StoredProcedure;
   SqlParameter Para_Type = myCommand.Parameters.Add("@sql",SqlDbType.VarChar);
   Para_Type.Value ="";
   SqlDataReader sqldr1 = myCommand.ExecuteReader();
   DataTable dt=new DataTable();
   dt.Columns.Add(new DataColumn("XXXX", typeof(string)));
   ……
   while (sqldr1.Read())
   {    
    dr = dt.NewRow();
    for (int i=0; i<sqldr1.FieldCount; i++)
    {      
     dr[i] = sqldr1[i].ToString();
    }
    dt.Rows.Add(dr);
   }

   DataView Source = new DataView(dt);
   DataGrid2.DataSource=Source;
   l_count.Text="共有"+Source.Count.ToString()+"條記錄";
   
   DataGrid2.DataBind();
   conn.Close();
     
  }
//使用DataSet綁定數據
  public void BindGrid(String sortfield)
  {   
   string sqlstring ="SELECT 用戶名, 姓名 FROM ryxx";
   conn.Open();
   SqlDataAdapter myCommand = new SqlDataAdapter(sqlstring, conn);
   DataSet ds = new DataSet();
   myCommand.Fill(ds,"ryxx");
   DataView Source = ds.Tables["ryxx"].DefaultView;
   Source.Sort = sortfield;
   DataGrid1.DataSource=Source;
   DataGrid1.DataBind();
   conn.Close();
  }
//執行除Select外的SQL語句
  private void ddl_xxxx_Bind()
  {   
   string updateshry;
   updateshry="update ryxx set 用戶名='fdsas', 姓名='kjdsj'";
   SqlCommand comshry=new SqlCommand(updateshry,conn);
   conn.Open();
   try
   {
    Cm.ExecuteNonQuery(); 
   }
   catch(SqlException E)
   {
    this.Response.Write("<script language=javascript>alert('異常信息:"+E.ToString()+"');</script>");
   }
   conn.Close();
  }
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章