C# .NET - Getting null value but when restarting the application getting the val

Asked By abinav shankar on 18-Jan-12 01:14 PM
Hi
 
I am using the code given below and what happens is when I run the application I didnt get any value but when i restart i am getting the values correctly and below is the code for binding the dropdown list what happens is when dtLeavetype has values but it is not getting populated correctly
private void bindLeaveStatus() 
  
    try 
    
      MySqlConnection con = new MySqlConnection(conn); 
      con.Open(); 
      MySqlDataAdapter daLeaveType = new MySqlDataAdapter("select leave_type_id,leave_type from leave_type", con); 
      DataTable dtLeavetype = new DataTable(); 
      daLeaveType.Fill(dtLeavetype); 
      ddlLeaveType.DataTextField = "leave_type"; 
      ddlLeaveType.DataValueField = "leave_type_id"; 
      ddlLeaveType.DataSource = dtLeavetype; 
      ddlLeaveType.DataBind(); 
      con.Close(); 
    }
kalpana aparnathi replied to abinav shankar on 18-Jan-12 01:30 PM

hi


Try this code

private void bindLeaveStatus()
  {
  if(!ispostback)
{
  try
  {
    MySqlConnection con = new MySqlConnection(conn);
    con.Open();
    MySqlDataAdapter daLeaveType = new MySqlDataAdapter("select leave_type_id,leave_type from leave_type", con);
    DataTable dtLeavetype = new DataTable();
    daLeaveType.Fill(dtLeavetype);
    ddlLeaveType.DataTextField = "leave_type";
    ddlLeaveType.DataValueField = "leave_type_id";
    ddlLeaveType.DataSource = dtLeavetype;
    ddlLeaveType.DataBind();
    con.Close();
  }
  catch(exception e)
{
}
 
}
D Company replied to abinav shankar on 18-Jan-12 02:07 PM
Hello Abinav,

By seeing your code, what i can say that you might have to check ispostback condition before you execute your code

check it and let me know if it is still not working

Regards
D
Jitendra Faye replied to abinav shankar on 18-Jan-12 11:40 PM
First check that where you have written your code.

If you have written your code in page _ Load() event then it should bind bind DataopDownList.

Call your function in Page_Load() event.

dipa ahuja replied to abinav shankar on 19-Jan-12 02:57 AM
Make sure you are calling the binding function in page_Load protected void Page_Load(object sender, EventArgs e)
{
  if (!IsPostBack)
  {
    bind();
  }
}
void bind()
{
   //code to bind dropdown
}