三个通用代码

类别:.NET开发 点击:0 评论:0 推荐:

public SqlConnection connection_database(string server,string database,string userid,string password)
  {
   string str_con;
   str_con="server="+server+";"+"database="+database+";"+"user id="+userid+";"+"

password="+password;
   try
   {
    SqlConnection sqlcon=new SqlConnection (str_con);
    sqlcon.Open();

    return sqlcon;
   }
   catch
   {
               MessageBox.Show("数据库连接不成功!请正确填写好数据库设置","错误",MessageBoxButtons.

OK,MessageBoxIcon.Stop);
    Application.Exit();//应用程序退出
    return null;
   }
         
  }
public DataView DvList(string logString,string tablename) //返回相应表的视图.
  {
   if( sqlconn.State == ConnectionState.Closed)
    sqlconn.Open(); 
   SqlDataAdapter myCommand = new SqlDataAdapter(logString, sqlconn);
   DataSet ds = new DataSet();
   try
   {
    myCommand.Fill(ds, "+tablename+");
   }
   catch
   {
    MessageBox.Show("error");
   }
   DataView Dv = new DataView();
   Dv = ds.Tables["+tablename+"].DefaultView;
   return Dv;
  } 
  
  public void Execute_SQL(string sql,SqlConnection sqlconn)//通用执行SQL函数
  {
   // 打开数据库连接
   if( sqlconn.State == ConnectionState.Open)
    sqlconn.Close(); 
   sqlconn.Open(); 
  SqlCommand cmd = new SqlCommand(sql, sqlconn);
   try
   {
    cmd.ExecuteNonQuery();
   }
   catch(SqlException ae)
   {
    MessageBox.Show(ae.Message.ToString());
   }
   cmd.Dispose();
  }
  public void show_listview_data(string select_str,string tablename,ListView lv)//通用的返回

树视图函数
  {
   //lv=new ListView();
   lv.Clear();
   this.sqlDataAdapter1=new SqlDataAdapter(select_str,this.sqlconn);
   sqlDataAdapter1.Fill(dataSet21,"+tablename+");
   //添加列名
   for(int i=0;i<dataSet21.Tables["+tablename+"].Columns.Count;i++)
   {
    lv.Columns.Add(dataSet21.Tables["+tablename+"].Columns[i].ColumnName.

ToString(),90,HorizontalAlignment.Left);

   }
   //添加行(数据库数据)
   for(int j=0;j<dataSet21.Tables["+tablename+"].Rows.Count;j++)
   {
    ListViewItem item=lv.Items.Add(dataSet21.Tables["+tablename+"].Rows[j][0].

ToString());
    item.Text=dataSet21.Tables["+tablename+"].Rows[j][0].ToString();
    for(int i=1;i<dataSet21.Tables["+tablename+"].Columns.Count;i++)
     item.SubItems.Add(dataSet21.Tables["+tablename+"].Rows[j][i].

ToString());    
   }
   lv.View=View.Details;
   
   
  }

 }

本文地址:http://com.8s8s.com/it/it45071.htm