I want to bind data from a SQL Server table column at page load in ASP.NET, but it is not working; code is working in a button click.
This is my code - can anyone help please?
if (!IsPostBack)
{
DataTable subjects = new DataTable();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
SqlDataAdapter adapter = new SqlDataAdapter("SELECT [name] FROM [supplier]", con);
adapter.Fill(subjects);
con.Open();
DropDownreturn.DataSource = subjects;
DropDownreturn.DataTextField = "name";
DropDownreturn.DataValueField = "name";
DropDownreturn.DataBind();
DropDownreturn.Items.Insert(0, new ListItem("Select", "NA"));
con.Close();
}
but it is not working; code is working in a button click.
When user press a button then it create a postback if Postback is enabled on button and you have placed !IsPostBack
check that may be preventing the code block to bind the dropdown.
To solve this issue.. At Page_Load, check if your button raised the postback then execute the code to bind the dropdown by following below suggested approach:
Which control caused the postback?
Way To Know Which Control Has Raised PostBack
if(IsPostBack)
{
if(postbackcontrol is button1)
{
//Bind dropdown
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.