开发者

DropDownList, List item then popullated from database

I have a DropDownList, when the form is first opened it selects the first entry found in the database. What I want it to do is display "Select." But I don't want the "Select" message to hold any value towards my database (I don't want the system to think this is an option to edit into the database).

What I'm trying at the moment is:

<asp:DropDownList ID="DropDownListEmployee" runat="server"  
                  AutoPostBack="True" 
                  OnSelectedIndexChanged="SelectionHasChanged"
                  DataSourceID="SqlDataSource1" DataTextField="Fullname"  
                  DataValueField="Employee_ID" Width="214px">
    <asp:ListItem>Select</asp:ListItem>

I have tried using:

dropdownList.DataBind();
dropdownList.Items.Insert(0, new ListItem("Select")); 

This solution kept setting "Select" into txt/data fields in which it did not belong, causing issues when trying to update, insert, or delete from database.

Also, how do I edit my posts so that it shows the code?

================ Code Behind File ================

namespace MyProject.Update
{
    public partial class UpdateEmployee : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void SelectionHasChanged(Object sender, System.EventArgs e)
        {

            string connectionString = WebConfigurationManager.ConnectionStrings["DBConnectionString1"].ConnectionString;


            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("Retreive", con);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int, 7));
            cmd.Parameters["@ID"].Value = Convert.ToInt32(DropDownListEmployee.SelectedValue.ToString());


            try
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();

                if (reader.Read())
                {
                    txt1.Text = (string)reader["1"];
                    txt2.Text = (string)reader["2"];
                    txt3.Text = (string)reader["3"];
                    txt4.Text = (string)reader["4"];
                    txt5.Text = (string)reader["5"];
                    txt6.Text = (string)reader["6"];
                    txt7.Text = (string)reader["7"];
                    txt8.Text = DropDownListEmployee.SelectedValue.ToString();
                }

                reader.Close();

            }

            catch (SqlException err)
            {
                // Replace the error with something less specific.
                // You could also log the error now.
                throw new ApplicationException("Data error.");
            }
            finally
            {
                con.Close();
            }
        }


        protected void UpdateEmployeeBTN_Click(object sender, EventArgs e)
        {
            string connectionString = WebConfigurationManager.ConnectionStrings["DBConnectionString1"].ConnectionString;


            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("Change", con);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int, 7));
            cmd.P开发者_开发百科arameters["@ID"].Value = Convert.ToInt32(DropDownListEmployee.SelectedValue.ToString());



            cmd.Parameters.Add(new SqlParameter("@1", SqlDbType.VarChar, 20));
            cmd.Parameters["@1"].Value = txt1.Text;

            cmd.Parameters.Add(new SqlParameter("@2", SqlDbType.VarChar, 20));
            cmd.Parameters["@2"].Value = txt2.Text;

            cmd.Parameters.Add(new SqlParameter("@3", SqlDbType.VarChar, 100));
            cmd.Parameters["@3"].Value = txt3_Address.Text;

            cmd.Parameters.Add(new SqlParameter("@4", SqlDbType.VarChar, 100));
            cmd.Parameters["@4"].Value = txt4.Text;

            cmd.Parameters.Add(new SqlParameter("@5", SqlDbType.Char, 12));
            cmd.Parameters["@5"].Value = txt5.Text;

            cmd.Parameters.Add(new SqlParameter("@6", SqlDbType.Char, 12));
            cmd.Parameters["@6"].Value = txt6.Text;

            cmd.Parameters.Add(new SqlParameter("@7", SqlDbType.VarChar, 50));
            cmd.Parameters["@7"].Value = txt7.Text;


            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                txtID.Text = Convert.ToString(cmd.Parameters["@ID"].Value);
            }
            catch (SqlException err)
            {
                // Replace the error with something less specific.
                // You could also log the error now.
                throw new ApplicationException("Data error.");
            }
            finally
            {
                con.Close();
            }

        }


Try using the AppendDataBoundItems attribute:

<asp:DropDownList ID="DropDownListEmployee" runat="server"  
                  AutoPostBack="True" 
                  OnSelectedIndexChanged="SelectionHasChanged"
                  DataSourceID="SqlDataSource1" DataTextField="Fullname"  
                  DataValueField="Employee_ID" Width="214px"
                  AppendDataBoundItems="true">
    <asp:ListItem Value="" Text="Select" />

This will allow you to add the databound items to the list without affecting anything you declared prior. Just make sure you add any items to the list before you call DataBind().

ListControl.AppendDataBoundItems Property

ADDED

Based on the code behind you pasted, I believe both ShankarSangoli and rudeovski ze bear have viable approaches for you. You need to check to ensure the user has made a selection in the DropDownList, and either throw an error if they didn't or provide some default value.


You should validate the selected value of the dropdownlist either on the client or server side before you insert it into database. I would suggest you to do it on the client side.

E.g. Using javascript/jquery you can check for the selected value.

if($("select[id*=DropDownListEmployee]").val() == "Select"){
   alert("Please select an employee);
   return false;//To prevent the form from submitting.
}

You can also check for selected value on the server side before inserting it into database.


From what i understand, it looks like you want to avoid the "select" item from going into the database.

So what you do is, in your submit event, you do a check to see if "DropDownListEmployee"'s selectedvalue != "Select".

You can also do this using javascript/jquery onclientclick of the submit button.

$("#submitButton").click(function () {
    if ($("#DropDownListEmployee").val() == "Select")
       // DO SOMETHING (or return false)
    else 
       return true;
});

in your codebehind button click event, do something like the following:

protected void submitButton_Click(object sender, EventArgs e)
{
    if (DropDownListEmployee.SelectedValue == "Select")
        // DO SOMETHING
    else
        // DO SOMETHING ELSE
}

Hope that helps


dropdownList.DataBind(); dropdownList.Items.Insert(0, new ListItem("Select")); should theoretically work for you. The side effects you describe lead me to believe there's a lot of other funky stuff going on in your code. You should edit your post to include more of your code so that we can provide better answers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜