简体   繁体   中英

Using ComboBox with a datagrid view

I am in the process of creating a c# front end for an existing Access DB. So far i have managed to connect to the DB with a connection string and then used a data adaptor to put one of the tables into a datagridview.

I want some of the columns to have a drop down list (combobox) that is bound to another table in the database.

Can anyone advise how i go about this.

I am using this as a way of learning to connect to databases using code so my knowledge is not great yet.

Can anyone tell me how to implement the combobox?

This is my code so far:

public void loadData() {

        OleDbConnection dbConnectionString;
        dbConnectionString = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\DATASTORE2012\OmegaDB\ISO\Problems_be.accdc;Persist Security Info=False");

        try
        {
            dbConnectionString.Open();
            MessageBox.Show("Connection Open");
            dbConnectionString.Close();
        } catch (Exception ex)
        {
            MessageBox.Show("Cannot Open Connection");
        }


        dbConnectionString.Open();
        string sqlString = "SELECT * FROM Problems";
        OleDbCommand command = new OleDbCommand(sqlString, dbConnectionString);
        var sqlDataAdapt = new OleDbDataAdapter(sqlString, dbConnectionString);
        using (DataTable dt = new DataTable())
        {
            sqlDataAdapt.Fill(dt);
            dataGridView1.DataSource = dt;

        }

I understand your needs now, here is a example in asp I found: her with a city-selection

your gridview in asp:

<asp:GridView ID="grvExcelData" runat="server" onrowdatabound="**GridView2_RowDataBound**">
    <HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
      <Columns>
          <asp:TemplateField>
              <ItemTemplate>
                 <asp:DropDownList ID="DrdDatabase" Width="100px" runat="server">
                 </asp:DropDownList>
              </ItemTemplate>
          </asp:TemplateField>
      </Columns>
  </asp:GridView>

code behind:

protected void **GridView2_RowDataBound**(object sender, GridViewRowEventArgs e)
    {
       string cities = "maxico,chennai,newdelhi,hongkong";
       string [] arr = cities.Split(',');
    // Instead of string array it could be your data retrieved from database.
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddl = (DropDownList)e.Row.FindControl("DrdDatabase");
            foreach (string colName in arr )
                ddl.Items.Add(new ListItem(colName));
        }
    }

So you have to change the asp from the textbox to dropdownlist see above.

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