0

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();
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Hama Mod
  • 33
  • 10
  • Are you receiving an error? – jtate Nov 12 '18 at 22:17
  • no i don't receive any errors – Hama Mod Nov 12 '18 at 22:21
  • Unrelated tips: SqlConnection and SqlDataAdapter are both IDisposable so each should be in a `using` block. Once you've done that, you don't need to Close the connection because it will be closed by the implicit Dispose as it exits the block. – Richardissimo Nov 13 '18 at 05:59
  • 2
    Please clarify *"it is not working"*: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. – Richardissimo Nov 13 '18 at 06:04
  • i fixed the problem thanks for helping – Hama Mod Nov 13 '18 at 20:40

1 Answers1

0

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 
  }
}
Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75