asp.net中数据绑定的写法

80酷酷网    80kuku.com

  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();
  }
 }
}

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: