Click here to Skip to main content
15,063,239 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need to add "Select" at index 0 without know DataTable columns count or name because this method in DataAccessLayer and will use later

C#
// ComboBox Fill Method
        public static void ComboBoxFill(ComboBox cbo, string Query, string cboDisplayMember, string cboValueMember)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand(Query, con);
            SqlDataReader dr = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(dr);
            cbo.DataSource = dt;
            cbo.DisplayMember = cboDisplayMember;
            cbo.ValueMember = cboValueMember;
            cbo.SelectedIndex = 0;
            con.Close();
        }


What I have tried:

C#
cbo.Items.Insert(0, "Select");
Posted
Updated 10-Jun-17 5:11am

I have solved this issue by the following code. Thanks for all ...


C#
public static void ComboBoxFill(ComboBox cbo, string Query, string cboDisplayMember, string cboValueMember)
    {
        con.Open();
        SqlCommand cmd = new SqlCommand(Query, con);
        SqlDataReader dr = cmd.ExecuteReader();
        DataTable dt = new DataTable();
        dt.Load(dr);
        DataRow drow = dt.NewRow();
        for (int i = 0; i < dt.Columns.Count ; i++)
        {
            if (dt.Columns[i].ColumnName == cboDisplayMember)
            {
                drow[i] = "Select";
            }
            else if (dt.Columns[i].ColumnName == cboValueMember)
            {
                drow[i] = 0;
            }
            else
            {
                drow[i] = null;
            }
        }

        dt.Rows.InsertAt(drow, 0);

        cbo.DataSource = dt;
        cbo.DisplayMember = cboDisplayMember;
        cbo.ValueMember = cboValueMember;
        cbo.SelectedIndex = 0;
        con.Close();
    }
   
First read the documentation
ComboBox Class (System.Windows.Forms)[^]

Then try this:

HWND hComboBox = GetDlgItem( m_hWnd, IDC_COMBOBOX );
int nIndex = SendMessage( hComboBox , CB_GETCURSEL, 0, 0 );
SendMessage( hComboBox , CB_GETLBTEXT, nIndex, (LPARAM)pFilename );
   
Comments
Walid Ibrahim Mohey-Eldin 10-Jun-17 11:08am
   
Thanks i have solved it by another code and i added it.
Thanks a lot for your interest
Richard MacCutchan 10-Jun-17 11:22am
   
That won't work in C#.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900