我正在开发Windows应用程序,其中我绑定了datagridview和textboxes控件。我想从load事件中检索两个不同表中的值。
这意味着存储在一个表中的datagridview值和存储在其他表中的文本框值。我该怎么办?
以下是我的form_load
事件代码:
private void Purchase_Load(object sender, EventArgs e)
{
bindgrid();
}
private void bindgrid()
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("select distinct product_id, product_name, qty, price, tax, discount, total from Purchasedetail union all select total from Purchase ", con);
da.SelectCommand = cmd;
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
da.Fill(ds, "Purchsedetail");
da.Fill(ds, "Purchase");
datagrid.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show("Exception caught : " + ex.Message.ToString());
}
finally
{
con.Close();
}
}
答案 0 :(得分:0)
您需要用分号分隔两个select命令。 (UNION尝试将两个结果集合并到一个结果集中,并且需要有两个具有相同模式的结果集)
try
{
con.Open();
string cmdText = @"select distinct product_id, product_name,
qty, price, tax, discount, total
from Purchasedetail;
select total from Purchase ";
SqlCommand cmd = new SqlCommand(cmdText, con);
// You pass the command and fill the DataSet.
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
// Now the Dataset contains two tables
datagrid.DataSource = ds.Tables[0];
// Of course this retrieves just the total from the first row,
// I suppose that your second query needs some kind of WHERE condition
// or some kind of aggregate function like SUM(Total)
textBox1.Text = ds.Tables[1].Rows[0][0].ToString();
}
catch (Exception ex)
{
MessageBox.Show("Exception caught : " + ex.Message);
}
finally
{
con.Close();
}