ListBox depulicates on page fire?
i am using C#,asp.net and sql server 2005.
now i want to show the value of one column in listbox during page load.
i did as follow:
Code:
string sqlvisa = "select visano from saudivisatbl";
con.Open();
SqlCommand sqlquery = new SqlCommand();
DataTable data = null;
sqlquery.Connection = null;
SqlDataAdapter ddapter = null;
sqlquery.CommandText = sqlvisa;
sqlquery.Connection = con;
data = new DataTable();
ddapter = new SqlDataAdapter(sqlquery);
ddapter.Fill(data);
for (int i = 0; i < data.Rows.Count; i++)
{
string data1 = data.Rows[i]["visano"].ToString();
listboxvisa.Items.Add(data1);
}
con.Close();
this code displays me correctly the value on list box.
now i want to assign the value of the selected value in the listbox into textbox1 on button click
Code:
protected void btnselectvalue_Click(object sender, EventArgs e)
{
textbox1.Text = listboxvisa.SelectedItem.ToString();
}
again the the value of the selected list box item is dispayed in the textbox1 on btn click, but the value of the listboxvisa becomes duplicated, when i click the button then again it will duplicate,
how do i prevent this duplication of on button click.
thanks
Re: ListBox depulicates on page fire?
On PageLoad first clear listbox then populate, or check if page is post back.
Re: ListBox depulicates on page fire?
for any ASP.NET related question, please post them on the ASP.NET forums in future:
http://www.vbforums.com/forumdisplay.php?f=31
code improvement:
from the code snippet you have given, there is no need to fill a datatable just for reading a column. This is inefficient both in terms of performance and memory.
it also does not make sense to keep the connection open whilst you are reading from the populated data table - you are consuming the connection longer than it is required. close the connection as soon as possible, then start reading the data from the datatable.
Furthermore, it is advisible to use SPROCS (Stored Procedures) rather than standard SQL commands as it is securer and faster in terms of performance plus less code maintainence on your ASP.NET application when it comes to the Database layer.
better way:
Code:
string sqlvisa = "select visano from saudivisatbl";
using (SqlCommand sqlquery = new SqlCommand(sqlvisa, con))
{
sqlquery.Connection.Open();
SqlDataReader reader = sqlquery.ExecuteReader(CommandBehavior.CloseConnection);
while(reader.Read())
{
listboxvisa.Items.Add(reader["visano"].ToString());
}
sqlquery.Connection.Close();
}
less code, more efficient and faster. :)