helloGoodDay
helloGoodDay

Reputation: 69

Select data from database then match the data to the dropdownlist

I have a Dropdownlist and I want to get the "users" specific "title" from the database and set it to that dropdownlist.

But instead of setting the title specific to the dropdownlists values within it, it just replaces the Select Title Text, instead of selecting the text Ms in the dropdownlist.

Are there any solution/s to set the title value in its rightful spot and not replacing the text in the dropdownlist?

Here is my aspx code

<asp:DropDownList ID="userTitle" runat="server">
    <asp:ListItem Text="Select Title" Value="-1"></asp:ListItem>
    <asp:ListItem Text="Mr" Value="Mr"></asp:ListItem>
    <asp:ListItem Text="Mrs" Value="Mrs"></asp:ListItem>
    <asp:ListItem Text="Miss" Value="Miss"></asp:ListItem>
    <asp:ListItem Text="Ms" Value="Ms"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorTitle" runat="server" ErrorMessage="User Title is required" InitialValue="-1" ForeColor="Red" ControlToValidate="userTitle"></asp:RequiredFieldValidator>

Here is my code-behind

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            PopulateTheFields();
        }
    }



private void PopulateTheFields()
        {
            String str;
            SqlCommand comm;

            con.Open();
            str = "select title from users where username='" + theUser + "'";
            comm = new SqlCommand(str, con);
            SqlDataReader reader = comm.ExecuteReader();

            if (reader.Read())
            {
                userTitle.SelectedItem.Text = reader["title"].ToString();
                reader.Close();
                con.Close();
            }
        }

Here is a print screen of proof.

https://i.sstatic.net/qgLc1.png

Thank you! Have a wonderful day

Upvotes: 0

Views: 1437

Answers (2)

jdw
jdw

Reputation: 1

It sounds like you want to do something like:

userTitle.SelectedValue = reader["title"].ToString();

Upvotes: 0

Christos
Christos

Reputation: 53958

You could try the following one:

userTitle.SelectedItem.Value = reader["title"].ToString();

instead of using

userTitle.SelectedItem.Text = reader["title"].ToString();

Furthermore, I would suggest you use a parameterized sql query instead of concatenating strings, to build you query. This approach will help you to avoid sql injections.

For instance, you could try the following one:

string query = "select title from users where username=@username";
SqlCommand command = new SqlCommand(query, con);
command.Parameters.Add(new SqlParameter("username",theUser));

Upvotes: 3

Related Questions