如何在c#中使用数据库中的数据填充datagridview的组合框 [英] How can I populate combobox of datagridview with data from database in c#

查看:64
本文介绍了如何在c#中使用数据库中的数据填充datagridview的组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

con = new SqlConnection(cs);
              con.Open();

              string ct = "select distinct RTRIM(faheads) from FA_Details ";

              cmd = new SqlCommand(ct);
              cmd.Connection = con;

              rdr = cmd.ExecuteReader();

              while (rdr.Read())
              {
                  // dataGridView1.Rows[0].Cells[2].Value.Add(rdr[0]);
                  DataGridViewComboBoxCell c =new DataGridViewComboBoxCell();
                  c.Items.Add(rdr[0]);
                  dataGridView1.Rows[0].Cells[2] = c;

              }
              con.Close();









但它只显示数据库中的一个值。





but it showing only one value from database.

推荐答案

对于从数据库返回的每条记录,您创建一个新的 DataGridViewComboBoxCell ,向其添加一个项目,并用新的单记录组合框替换第一行的第三个单元格。



您需要在循环外移动单元格创建和赋值。



For each record returned from the database, you're creating a new DataGridViewComboBoxCell, adding one item to it, and replacing the third cell of the first row with the new single-record combobox.

You need to move the cell creation and assignment outside of the while loop.

const string query = "select distinct RTRIM(faheads) from FA_Details";

var c = new DataGridViewComboBoxCell();
dataGridView1.Rows[0].Cells[2] = c;

using (var con = new SqlConnection(cs))
using (var cmd = new SqlCommand(query, con))
{
    con.Open();
    
    using (var rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
    {
        while (rdr.Read())
        {
            c.Items.Add(rdr[0]);
        }
    }
}


你好,



假设你有一个datagridview,并且有一个名为

cmbproduct的组合框,如果你想绑定数据集中的组合框值,那么

Hello ,

suppose you have one datagridview and there one comboboxcolumn named as
cmbproduct and if you want to bind the combobox value from dataset then
<br />
<br />
 cmbproduct.DataSource = dsproduct.Tables[0].Columns[0].Table.DefaultView;<br />
 cmbproduct.ValueMember = "PId"; <br />
 cmbproduct.DisplayMember = "Pname";<br />



将此代码放在要加载组合框的位置。 />


谢谢

Animesh


put this code where you want to load the combobox .

thanks
Animesh


这篇关于如何在c#中使用数据库中的数据填充datagridview的组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆