首页 > 编程 > .NET > 正文

asp.net中数据绑定的写法

2024-07-10 13:06:25
字体:
来源:转载
供稿:网友


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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表