【C#.NET】dataGridView查詢SQL資料方法
public void selecetdata()//如果不是static 就要例項化才能呼叫 ,
{
try
{
string tablename;
tablename = "t_bd_item_cls";
if (cbtablename.Text == "類別資料")
{
tablename = "select item_clsno 類別編號,item_clsname 類別名稱,profit_rate 毛利率 from t_bd_item_cls";
}
else if (cbtablename.Text == "商品資料")
{
tablename = "select * from t_bd_item_info";
}
string ConStr =
"server=" + tbip.Text + //資料庫地址
"," + tbduankou.Text + //資料庫埠
"; user id=" + tbuser.Text + //訪問使用者名稱
"; pwd = " + tbpwd.Text + //資料庫密碼
"; database =" + cbdatabase.Text; //資料庫名
預防超時
//connAll.conmmsy = "Data Source=" + connAll.ip + "," + connAll.duankou
// + "; user id = mmsy; pwd = mmsy2950001; database = " + connAll.dataBase+ ";Trusted_Connection=Yes;Connection Timeout=60000";
// string ConStr = "server=yoti,6060; user id = sa; pwd = 2950001; database = hbposev9";
SqlConnection con = new SqlConnection(ConStr); //例項化SQLconnection類。連線資料庫
string SQLstr = tablename; //設定SQL語句
// string SQLstr = "select "+ ziduan+ " from "+ tablename; //設定SQL語句
// string SQLstr = "select * from t_bd_item_cls";
SqlDataAdapter ada = new SqlDataAdapter(SQLstr, con);//建立SQL語句與資料庫的連線
DataSet ds = new DataSet(); //例項化Datatable類
ada.Fill(ds); //新增SQL並且執行
this.dataGridView1.DataSource = ds.Tables[0].DefaultView;//顯示資料
dataGridView1.DefaultCellStyle.BackColor = Color.Honeydew;//設定背景顏色
}
catch
{
return;
}
}
//查詢資料按鈕事件
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(tbip.Text))
{
MessageBox.Show("親!必須輸入計算名或IP哦");
tbip.Focus();
}
else if (string.IsNullOrWhiteSpace(tbduankou.Text))
{
MessageBox.Show("親!資料庫埠不能為空噢");
tbduankou.Focus();
}
else if (string.IsNullOrWhiteSpace(tbuser.Text))
{
MessageBox.Show("親!你忘記輸入登入名了!");
tbuser.Focus();
}
else if (string.IsNullOrWhiteSpace(tbpwd.Text))
{
MessageBox.Show("親!你沒輸資料庫密碼");
tbpwd.Focus();
}
selecetdata();
}
public void sqldate()
{
try
{
SqlConnection con = new SqlConnection(ClassConnAll.conmmsy); //例項化SQLconnection類。連線資料庫
string SQLstr = "select * from Hion_AreaNew ";; //設定SQL語句
SqlDataAdapter ada = new SqlDataAdapter(SQLstr, con);//建立SQL語句與資料庫的連線
DataSet ds = new DataSet(); //例項化Datatable類
ada.Fill(ds); //新增SQL並且執行
dataGridView1.DataSource = ds.Tables[0].DefaultView;//顯示資料
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "親,沒有資料哦!請檢查下查詢條件!");
return;
}
finally
{ }
}