下拉值在提交后消失

本文关键字:消失 提交 | 更新日期: 2023-09-27 18:18:34

我有一个文本框,其值进入下拉按钮单击。问题是,当我填写所有数据并提交表单时。当我第二次看到这个值时它从下拉框中消失了。我应该怎么做,使值得到在下拉修复。请参考代码:

 <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>
            &nbsp;&nbsp;&nbsp;
                    <asp:Button ID="btnAddDropDown" runat="server" Width="63" Text="Add" CausesValidation="false" OnClick="btnAddDropDown_Click1" />
        </td>
    </tr>

同样,参考后面的代码:-

 protected void ddlLocation_SelectedIndexChanged(object sender, EventArgs e)
{
    if (ddlLocation.SelectedItem.Text == "Other")
    {
        txtOtherCity.Visible = true;
    }
    else
    {
        txtOtherCity.Visible = false;
    }
}
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
    string city = txtOtherCity.Text.Trim();
    if (!string.IsNullOrEmpty(city))
    {
        ddlLocation.Items.Add(new ListItem(city, city));
    }
}

下拉值在提交后消失

必须将文本框中的值存储到表dbo中。数据库中的城市。下次当你回到同一页面时,下拉菜单将从数据库中获取数据。

然后在btnAddDropDown_Click1()上,您应该将'txtOtherCity' TextBox中的城市值插入到相应的表中,然后再次绑定该城市的DropDown。就像

 protected void btnAddDropDown_Click1(object sender, EventArgs e)
        {
          string strconnection =            System.Configuration.ConfigurationManager.AppSettings["YourConnectionString"].ToString();
            string city = txtOtherCity.Text.Trim();
            DataSet ds=new DataSet();
            if (!string.IsNullOrEmpty(city))
            {
                // Your code to insert the value of the city from the 'txtOtherCity'           `TextBox` to the respective table
                 //Edit: this is a very rudimentary code
                 string query = "INSERT INTO Career.Location (State) " + 
                       "VALUES (@city) ";
        // create connection and command
          using(SqlConnection cn = new SqlConnection(strconnection))
          using(SqlCommand cmd = new SqlCommand(query, cn))
           {
            // define parameters and their values
            cmd.Parameters.Add("@city", SqlDbType.VarChar, 50).Value = city;
            // open connection, execute INSERT, close connection
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();
            }
            query = "select State from Career.Location";
            using(SqlConnection cnn = new SqlConnection(strconnection))
            using(SqlCommand cmdd = new SqlCommand(query, cnn))
           {  
            SqlDataAdapter adp = new SqlDataAdapter(cmdd);            
            cnn.Open();
            adp .Fill(ds);
            cnn.Close();
            }
             ddlLocation.DataSource=ds;
             ddlLocation.DataTextField = "State";
             ddlLocation.DataValueField = "State";
             ddlLocation.DataBind();
            }
        }

是否具有在DB中插入数据的功能(而不仅仅是在下拉列表中添加新项)?您必须在适当的表中插入城市,以便以后能够看到它。

实现取决于您的体系结构,DAL的实现等。例如,如果您正在使用ADO。. NET时,可以使用存储过程:

将值插入表中。

CREATE PROCEDURE Add_City @CityName varchar(50), @StateID int AS BEGIN INSERT INTO dbo.Cities (CityName, StateID) values (@CityName, @StateID) END GO

然后从应用程序中调用它,像这样:

using (SqlConnection con = new SqlConnection("the connection string"))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "Add_City";
            cmd.Parameters.Add("@CityName", SqlDbType.VarChar).Value = txtCity.Text.Trim();
            cmd.Parameters.Add("@StateID", SqlDbType.Int).Value = CountryId;
            cmd.Connection = con;
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                // lblMessage.Text = "City inserted successfully!";
            }
            catch (Exception ex)
            {
                throw ex; // Or log or handle somehow the exception
            }
        }

我得到了这个解决方案的答案,请参阅代码供您参考:-

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();
    }
}
protected void ddllocation1_SelectedIndexChanged(object sender, EventArgs e)
{
    string country = "India";
    var cities = _helper.GetLocations(country, ddllocation1.SelectedValue);
    cities.Insert(0, "--Select--");
    cities.Insert(1, "Other");
    ddlLocation.DataSource = cities;
    ddlLocation.DataBind();
}
protected void btnAddDropDown_Click1(object sender, EventArgs e)
{
    using (SqlConnection con = new SqlConnection(constring))
    {
        con.Open();
        //BindContrydropdown();
        //if (txtOtherCity.Text != "")
        //{
        //    txtOtherCity.Text = "";
        //}
        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 = ddlLocation.SelectedItem.ToString();
        cmd.Connection = con;
        try
        {
            // con.Open();
            cmd.ExecuteNonQuery();
            BindContrydropdown();
            // lblMessage.Text = "City inserted successfully!";
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);//You Can Haave Messagebox here
        }
        finally
        {
            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>
            &nbsp;&nbsp;&nbsp;
                    <asp:Button ID="btnAddDropDown" runat="server" Width="63" Text="Add" CausesValidation="false" OnClick="btnAddDropDown_Click1" />
        </td>
    </tr>

这解决了我的,请参见存储过程:-

Alter PROCEDURE [dbo].[Add_CityforLocation]
-- Add the parameters for the stored procedure here
@ID int,
@CountryName nvarchar(100),
@StateName nvarchar(100),
@CityName varchar(100)

开始插入事业。位置(CountryName, StateName, CityName)值(@CountryName,@StateName,@CityName)结束去