从DataTable到gridview的值作为组合框

时间:2012-04-04 17:13:47

标签: c# mysql

我正在尝试从我的数据表中获取一列,以在网格视图中显示为组合框。还需要有能力用小集合填充组合来选择。当我从Gui绑定它时它不会显示值,所以我尝试编程,但似乎无法找到正确的代码。

 connection2 = new MySqlConnection(ConnectionString2);


        try
        {
            string proid = txtbxProjId.Text;

            //prepare query to get all records from items table
            string query2 = "select sl.sample_id As sample_id, sl.sample_number As Sample_Number, sl.sample_date As Sample_Date, sl.sample_time As Sample_Time, sl.sample_comments As Sample_Comments FROM spt_sample_login sl Where project_id = '"+proid+"'";



            //prepare adapter to run query
            adapter2 = new MySqlDataAdapter(query2, connection2);
            adapter3 = new MySqlDataAdapter(query2, connection2);

            //create a DataTable to hold the query results
            DataTable dTable2 = new DataTable();
            DataSet DS2 = new DataSet();

            //fill the DataTable


            //get query results in dataset
            adapter2.Fill(dTable2);
            adapter3.Fill(DS2);



            //return datatable with all records
            //BindingSource to sync DataTable and DataGridView


                //set the BindingSource DataSource
            GridView1.DataSource = dTable2;


            this.GridView1.Columns["sample_id"].Visible = false;

            this.GridView1.Columns["Sample_Type"].DisplayIndex = 4;
           this.GridView1.Columns["Sample_Type"].Visible = true;










            //set the DataGridView DataSource












        }
        catch (MySqlException ex)
        {


        }
    }

这有效,但将Sample_Type显示为一个文本框,我希望它是一个组合,F,P Q,B作为选项。

谢谢 布伦特

1 个答案:

答案 0 :(得分:0)

您必须将ComboBox放在itemTemplate中,并且必须在rowDataBound事件期间填充它。

从我目前的项目中快速例证:

DropDownList ddlRole = (DropDownList)e.Row.FindControl("ddlRole");

ddlRole.DataSource = GetTruckersRoles();

string[] rolesList = Roles.GetRolesForUser((string)gvTruckers.DataKeys[e.Row.RowIndex][0]);
if (rolesList.Length > 0)
{
    //If user is not in any roles, dont' do this
    ddlRole.SelectedValue = rolesList[0];
}

ddlRole.DataBind();

只需根据您的情况调整代码