单击按钮时,下拉框失去其值
本文关键字:失去 按钮 单击 | 更新日期: 2023-09-27 18:18:47
我有两个下拉列表。第一个是州的,第二个是市的。当我选择州时,相应的城市将在下一个下拉列表中填充。我有一个选项,通过文本框上的按钮单击,同时从城市下拉列表中选择其他选项添加更多的城市。
问题是,每当我从文本框中添加城市,它被插入到各自的状态,下拉列表也失去了它的值。我试着调试,但找不到确切的问题。
请参考代码:
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Add_CityforLocation";
cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = 0;
cmd.Parameters.Add("@CountryName", SqlDbType.VarChar).Value = "India";
cmd.Parameters.Add("@CityName", SqlDbType.VarChar).Value = txtOtherCity.Text.Trim();
cmd.Parameters.Add("@StateName", SqlDbType.VarChar).Value = ddllocation1.SelectedItem.ToString();
cmd.Connection = con;
try
{
cmd.ExecuteNonQuery();
BindContrydropdown();
}
catch (Exception ex)
{
Response.Write(ex.Message);//You Can Haave Messagebox here
}
finally
{
con.Close();
}
}
}
protected void BindContrydropdown()
{
//conenction path for database
//string connection = WebConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select Id,CityName From Career.Location", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddllocation1.DataSource = ds;
ddllocation1.DataTextField = "CityName";
ddllocation1.DataValueField = "Id";
ddllocation1.DataBind();
ddllocation1.Items.Insert(0, new ListItem("--Select--", "0"));
ddllocation1.Items.Insert(1, new ListItem("--OTHER--", "0"));
con.Close();
}
}
同样,参见HTML:-
<tr>
<td class="td">Location/State</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddllocation1" OnSelectedIndexChanged="ddllocation1_SelectedIndexChanged" runat="server" AutoPostBack="true"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="RequiredFieldValidator1" ControlToValidate="ddllocation1" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="td">Location/City</td>
<td>
<asp:DropDownList CssClass="txtfld-popup" ID="ddlLocation" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlLocation_SelectedIndexChanged"></asp:DropDownList>
<asp:RequiredFieldValidator CssClass="error_msg" ID="reqLocation" ControlToValidate="ddlLocation" runat="server" ErrorMessage="Please enter location" InitialValue="--Select--" SetFocusOnError="true"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtOtherCity" runat="server" Visible="false" CssClass="txtfld-popup"></asp:TextBox>
<asp:Button ID="btnAddDropDown" runat="server" Width="63" Text="Add" CausesValidation="false" OnClick="btnAddDropDown_Click1" />
</td>
</tr>
试试这个
try
{
if(!IsPostBack)
{
cmd.ExecuteNonQuery();
BindContrydropdown();
}
}