简体   繁体   中英

Filling of ComboBox with Dataset

When am trying to fill Combobox

con.Open();
da = new SqlDataAdapter("Mt_Post_select",con);
//Mt_Post is Stored procedure with Select Command
ds1 = new DataSet();
da.Fill(ds1, "Mt_Post");
// The table has only one row
comboBox1.DataSource = ds1.Tables[0];
comboBox1.DisplayMember = "Mt_Post";

It bind But shows instead of data it having System.Data.DataRowView

What is the wrong this code Please anyone tell me

Replace Mt_Post in comboBox1.DisplayMember = "Mt_Post"; with the name of column whose value you would like to display.

I hope the following sample helps;

        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Email");
        dt.AcceptChanges();

        DataRow dr0 = dt.NewRow();
        dr0[0] = "Kadir Sumerkent";
        dr0[1] = "kadir@sumerkent.com";

        DataRow dr1 = dt.NewRow();
        dr1[0] = "Kadir Sumerkent 2";
        dr1[1] = "kadir@sumerkent2.com";

        dt.Rows.Add(dr0);
        dt.Rows.Add(dr1);
        dt.AcceptChanges();

        comboBox1.DisplayMember = "Name";
        comboBox1.ValueMember = "Email";
        comboBox1.DataSource = dt;

Let's try this:

Suppose your Stored Procedure is like the code below:

SELECT 
     Users.User_name AS username
     Users.User_Code AS userID
FROM Users
-- WHERE CONDITONS ARE APPLIED

Now in order to Fetch this DataSet you are going to do as follows:


// YOUR OWN CODE
con.Open();
da = new SqlDataAdapter("Mt_Post_select",con);
//Mt_Post is Stored procedure with Select Command
ds1 = new DataSet();

// JUST FILL THE DataSet in THIS WAY
da.Fill(ds1);

// JUST TO MAKE SURE WE HAVE AN EMPTY COMBOBOX
comboBox1.Items.Clear();
comboBox1.DataSource = null;

// NOW POPULATE comboBox1 LIKE THIS
if (ds.Tables[0].Rows.Count  > 0)
{
  comboBox1.DataSource = ds1.Tables[0];
  comboBox1.DisplayMember = "username";
  comboBox1.ValueMember = "userID"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM