如何将值从下拉列表和复选框添加到gridview

时间:2019-06-04 13:40:10

标签: c# asp.net gridview webforms

编辑:添加了代码和图像参考`公共局部类DodavanjeNamirnice:System.Web.UI.Page     {

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DataTable dtTemp = new DataTable(); ;
            dtTemp.Columns.Add(new DataColumn("Namirnica", typeof(string)));
            dtTemp.Columns.Add(new DataColumn("Mjerna Jedinica", typeof(string)));

            Session["Data"] = dtTemp;
        }
    }

    protected void BindGrid()
    {
        string constr = ConfigurationManager.ConnectionStrings["Data Source =.\\SQLEXPRESS; Initial Catalog = pra; Integrated Security = True"].ConnectionString;
        string query = "SELECT * FROM Namirnica";
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
            {
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        var dataTableFromSession = Session["Data"] as DataTable;
        var dataRow = dataTableFromSession.NewRow();
        dataRow["Namirnica"] = DropDownList2.SelectedItem.Text;
        dataRow["Mjerna Jedinica"] = CheckBoxList1.SelectedItem.Text;
        dataTableFromSession.Rows.Add(dataRow);
        Session["Data"] = dataTableFromSession;
        GridView1.DataSource = dataTableFromSession;
        GridView1.DataBind();
    }
}`I got 2 dropdownlists , first one is filtering data in the 2nd,also 1st dropdownlist is connected to sql table as is the other one.

我有一个复选框,用于显示另一个表中的数据。 我的问题是:我想将我从第二个下拉列表和复选框列表中选择的值添加到Webform的gridview中。

我尝试手动添加新列,但最终只显示了下拉列表中的第一个值,也仅显示了复选框列表中的一个值。 https://gyazo.com/59ea939b26deb55d3f31e68057249253

1 个答案:

答案 0 :(得分:0)

设置一种方法,将选定或创建的单元格更改为DataGridViewComboBoxCell,然后向其提供下拉列表的数据源。

 //could be whatever event you want such as the creation of a new DataRow in your DataGridView
 private void gridView1_CellClick(object sender, DataGridViewCellEventArgs e)
 {
         dataGridView1[e.ColumnIndex, e.RowIndex] = new DataGridViewComboBoxCell();
         DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
         cb.DataSource = dataSource;
 }

您可以对复选框执行类似的操作,但改用新的DataGridViewCheckBoxCell()。用户选择了一个值后,您可以根据需要将其切换回常规单元格。