【问题标题】:How to add values from dropdownlist and checkbox to gridview如何将下拉列表和复选框中的值添加到gridview
【发布时间】:2019-10-20 01:23:27
【问题描述】:

编辑:添加了代码和图像参考`public partial class 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.

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

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

【问题讨论】:

    标签: c# asp.net gridview webforms


    【解决方案1】:

    设置一种方法,将选定或创建的单元格更改为 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()。用户选择一个值后,您可以根据需要将其切换回常规单元格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-28
      • 1970-01-01
      相关资源
      最近更新 更多