下拉值始终选择第一个值

时间:2018-10-10 06:47:45

标签: c# asp.net

下面是我的行更新事件代码。我的问题是当我选择下拉列表并将其保存到数据库时,它总是只选择第一个选择。

    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {


                int devopsid = Convert.ToInt16(GridView1.DataKeys[e.RowIndex].Values["devopsid"].ToString());

                foreach (GridViewRow row in GridView1.Rows)
                {
                    if (row.RowType == DataControlRowType.DataRow)
                    {
                        for (int i = 5; i < row.Cells.Count; i++)
                    {
                            DropDownList ddl = new DropDownList();
                            ddl.ID = "ddl " + row.Cells[0].Text;
                            // ddl.SelectedIndex = 0;
                            // ddl.Items.Add("Yes");
                            //ddl.Items.Add("No");
                            // ddl.SelectedIndex = 0;
                            ListItem item1 = new ListItem("Yes", "1");
                            ListItem item2 = new ListItem("No", "0");

                            List<string> values = new List<string>() { "Yes", "No" };
                            ddl.DataSource = values;

                            ddl.DataBind();

                            row.Cells[i].Controls.Add(ddl);
                            string ddlselected = ddl.SelectedValue;
                            if (GridView1.HeaderRow.Cells[i].Text == DropDownList1.SelectedItem.Text.Trim())
                            {
                                string query = " update devopstable set  " + GridView1.HeaderRow.Cells[i].Text + "  = '" + ddlselected + "' where devopsid=@devopsid ";
                                SqlCommand cmd = new SqlCommand(query, cnn1);
                                cnn1.Open();
                                cmd.Parameters.AddWithValue("@devopsid", devopsid);
                                cmd.ExecuteNonQuery();
                                cnn1.Close();
                            }


                    }
                }
            }
                GridView1.EditIndex = -1;
                FillGrid();


        }

2 个答案:

答案 0 :(得分:1)

尝试在page_load的IsPostback中编写保存方法

示例:

protected void Page_Load(object sender, EventArgs e)
{

  if (IsPostBack)
  {
      // wrap your save method in function and call here
  }

}

答案 1 :(得分:0)

当页面不在drop-down上的PostBack上时,将数据绑定到您的PageLoad

protected void Page_Load(object sender, EventArgs e)
{

  // be careful it should be not post-back.
  if (!IsPostBack)
  {
      // bind and set data source of your drop-down here
  }

}