在组合框中选择项目时,从数据库填充数据网格视图

时间:2013-05-13 08:49:01

标签: c# winforms

我有一个具有申请号的组合框。现在,当我在组合框中选择1个请购项目如r001时,其信息应填入下面的数据网格中。我已经使用了一个stroed程序。但我不知道如何将数据网格视图控件绑定到信息。

代码:

private void cmbreqno_SelectedIndexChanged(object sender, EventArgs e)
    {

        cmd.Connection = con;
        if (con.State != ConnectionState.Open)
        {
            con.Open();
        }

        txtcc.Text = "";
        int selection = Convert.ToInt16(((KeyValuePair<string, string>)(cmbreqno.SelectedItem)).Key);
        if (selection.ToString() != "")
        {

            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "itemname";
            cmd.Parameters.AddWithValue("@req_no", selection);
            dsitemname.Clear();
            adp = new SqlDataAdapter(cmd);
            adp.Fill(dsitemname);
            txtcc.Text = dsitemname.Tables[1].Rows[0]["costcenter_no"].ToString();
            txtcc.Tag = dsitemname.Tables[1].Rows[0]["costcenter_id"].ToString();

            cmd.Parameters.Clear();
}

存储过程:

alter proc itemname
(
    @req_no int
)
as begin
select item_name,brand_name,quantity,requisitionitem.item_cost
from requisitionitem left outer join item
on requisitionitem.item_id=item.item_id
where requisitionitem.req_no=@req_no
end

2 个答案:

答案 0 :(得分:0)

应该如下:

            con.Open();
            int selection = Convert.ToInt16(((KeyValuePair<string, string>)(cmbreqno.SelectedItem)).Key);
            cmd = new SqlCommand("storedProcedureName", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@req_no",selection);
            da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
            cmd.ExecuteNonQuery();

希望它有用。

答案 1 :(得分:0)

只需将您的DataTable数据绑定到DataGridView

dataGridView1.DataSource = null; //clear old one
dataGridView1.Rows.Clear(); //remove old rows
dataGridView1.DataSource = dsitemname.Tables[0];