missellorin
missellorin

Reputation: 389

populating GridView with sql data

I need to select from my users table the username of the user that has the roleID that I will have to get from the dropdownlist. The data are not appearing in the GridView. Can't see what's wrong, help me please. Already tried 2 ways

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
   {
       SqlConnection con = new SqlConnection(cs);
       con.Open();
       SqlCommand cmd = new SqlCommand("select username from tblUser where roleID like '" + DropDownList1.SelectedValue + "'", con);

       SqlDataAdapter da = new SqlDataAdapter(cmd);
       DataTable dt = new DataTable();
       da.Fill(dt);
       GridView2.DataSource = dt;
       GridView2.DataBind();
       con.Close();
   }

protected void Button2_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(cs);
    con.Open();
    SqlCommand cmd = new SqlCommand("select username from tblUser where roleID like '" + DropDownList1.SelectedValue + "'", con);

    SqlDataReader reader = cmd.ExecuteReader();

    GridView2.DataSource = reader;
    GridView2.DataBind();
    con.Close();
}

Upvotes: 0

Views: 14684

Answers (1)

missellorin
missellorin

Reputation: 389

Okay, so this one worked for me. And you also must check the sources. Like what happened to my GridView, it says AutoGenerateColumns = false, I removed it. And it all worked!

protected void Button2_Click(object sender, EventArgs e)
{
    string cs = ConfigurationManager.ConnectionStrings["roleDB"].ConnectionString;
    SqlConnection con = new SqlConnection(cs);
    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "select username from tblUser where roleID like '" + DropDownList1.SelectedValue + "'";
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    GridView2.DataSource = dt;
    GridView2.DataBind();
    con.Close();
}

Upvotes: 2

Related Questions