I want to bind GridView
at run time when the DataSource
is selected and when the user select a option from a DropDownList
. But the selected table or connection is not made properly.
Please check the following code and give me the appropriate solution.
public partial class index : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection();
string option = "";
protected void Page_Load(object sender, EventArgs e)
{
option = selectProductdropdown.SelectedValue;
}
protected void Button1_Click(object sender, EventArgs e)
{
Label2.Text = option;
if (option == "Books")
{
Label3.Text = option;
conn.ConnectionSt开发者_C百科ring = ConfigurationManager.ConnectionStrings["booksconnectionstring"].ConnectionString;
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * from books", conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter reader = new SqlDataAdapter(cmd);
DataSet s = new DataSet();
reader.Fill(s);
GridView1.DataSource = s;
GridView1.DataBind();
conn.Close();
}
The problem is in your page_load event, where you are assigning a value to option. When you click the button, the page_load will call again and your value will reset.
it should be...
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
option = selectProductdropdown.SelectedValue;
}
OR it would be better if you do like..
if (selectProductdropdown.SelectedValue == "Books")
because you are probably emptying option at each page load.
Avoid the public variable string option = "";
Instead define the same in the Click Event and get the selected value there
option = selectProductdropdown.SelectedValue;// move to click event
Because when the button is clicked the dropdown would be reset (assuming you have not shown the dropdown bind code here)
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
option = selectProductdropdown.SelectedValue;
}
You had omitted this line:
cmd.ExecuteReader();
Place it between the statements, like this:
SqlCommand cmd = new SqlCommand("SELECT * from books", conn);
cmd.ExecuteReader(); // <-- HERE
cmd.CommandType = CommandType.Text;
精彩评论