Get the selected index and selected value of a ListBox - c#

I am having problems getting the selected index and selected value of a ListBox. I am trying to fill the list box with values from a database and after this, on selected index change event, I cannot extract the selected index and selected value. Instead, I get a selected index of -1 and the selected value does not contain a value.
Here is a screenshot before clicking any item in the ListBox:
And this is a screen shot taken after clicking an item:
Here is the c# code:
public partial class std_Course_dashboard : System.Web.UI.Page
{
int index;
string value;
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Session["uid"].ToString();
Label2.Text = Session["crs_id"].ToString();
ListBox1.Items.Clear();
SqlDataReader r;
SqlCommand cmd = new SqlCommand("select lecture_text, lecture_Title,lecture_No from Lecture where course_ID='" + Convert.ToInt32(Session["crs_id"]) + "'", con);
con.Open();
ListBox1.DataSource = cmd.ExecuteReader();
ListBox1.DataTextField = "lecture_Title";
ListBox1.DataValueField = "lecture_No";
ListBox1.DataBind();
con.Close();
ListBox1.Items.Insert(0, new ListItem("--Select Customer--", "0"));
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
value = ListBox1.SelectedValue;
index = ListBox1.SelectedIndex;
Label3.Text = value;
Label4.Text = index.ToString();
}
}

This is because of clearing the items each time the page makes request
ListBox1.Items.Clear();
you can remove this line of code and adding if(!IsPostBack) so that data loads only for the first time when page loads
if(!IsPostBack)
{
Label1.Text = Session["uid"].ToString();
Label2.Text = Session["crs_id"].ToString();
SqlDataReader r;
SqlCommand cmd = new SqlCommand("select lecture_text, lecture_Title,lecture_No from Lecture where course_ID='" + Convert.ToInt32(Session["crs_id"]) + "'", con);
con.Open();
ListBox1.DataSource = cmd.ExecuteReader();
ListBox1.DataTextField = "lecture_Title";
ListBox1.DataValueField = "lecture_No";
ListBox1.DataBind();
con.Close();
ListBox1.Items.Insert(0, new ListItem("--Select Customer--", "0"));
}

If you place a breakpoint within your Page_Load, you will notice that it hits on every single PostBack. Since this happens, your code is designed such that your ListBox gets rebound with data every time you PostBack - including when you select a new index in your ListBox. This is what is causing your SelectedIndex to get reset.
What you need to do is only bind your ListBox once. You can achieve this by checking the Page.IsPostBack condition. If the PostBack is not caused by the client, bind the ListBox.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Label1.Text = Session["uid"].ToString();
Label2.Text = Session["crs_id"].ToString();
ListBox1.Items.Clear();
SqlDataReader r;
SqlCommand cmd = new SqlCommand("select lecture_text, lecture_Title,lecture_No from Lecture where course_ID='" + Convert.ToInt32(Session["crs_id"]) + "'", con);
con.Open();
ListBox1.DataSource = cmd.ExecuteReader();
ListBox1.DataTextField = "lecture_Title";
ListBox1.DataValueField = "lecture_No";
ListBox1.DataBind();
con.Close();
ListBox1.Items.Insert(0, new ListItem("--Select Customer--", "0"));
}
}

Related

selected index value in C# with combobox with database

I am new in c# and I have a question.
I want to select a value from a combobox and it should show in a label it's age.
What I do is this:
public void FillCombo()
{
SqlDataAdapter adap = new SqlDataAdapter("Select * from customers",con);
DataTable dt = new DataTable();
adap.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "name";
comboBox1.ValueMember = "id";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd1 = new SqlCommand("Select * from customers where name=#name ", con);
cmd1.Parameters.AddWithValue("#name",comboBox1.SelectedItem));
int i= cmd1.ExecuteNonQuery();
if (i > 0)
{
SqlDataReader sqlrdr = cmd1.ExecuteReader();
while (sqlrdr.Read())
{
String age= sqlrdr["age"].ToString();
label1.Text = age;
}
}
else{
MessageBox.Show("no value");
}
con.Close();
}
It shows no value message , even if i have values in database. What can I do?
When you set the DataSource to a DataTable then every item in the combobox is a DataRowView. So you already have the info about the age of the current customer in the combobox. No need to make another call to the database.
You just need to use the SelectedItem property to retrieve the info about the age field or any other field present in the DataSource
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView rv = l.SelectedItem as DataRowView;
// For safety, always check for null.
// It is possible that SelectedIndexChanged
// will be called even when there is no selection in the combobox
if(rv != null)
{
label1.Text = rv["age"].ToString();
....
}
}
Try this to obtain index,value and selected name:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
int selectedValue = (int)cmb.SelectedValue;
ComboboxItem selectedName = (ComboboxItem)cmb.SelectedItem;
}

label does not behave properly

I am devleoping a online airline reservation system in which i have two dropdownlists to select source and destinations and a label .this label will show " there are no flights" if there are no matching routes retrieved from the database (in this case its sqlserver 2008).i have written the following code which tries to do so, but when i postback or refresh the page the label with " there are no flights" is till visible.what is wrong with my code please anyone help me with that.
public partial class Dropdndemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con=new SqlConnection("Data Source=KUNDAN-PC\\SQLEXPRESS;Initial Catalog=Ars2.1.2;Integrated Security=True");
//string Sqlcmnd="select Source from Ars2.1.2.dbo.Scheduling";
con.Open();
if (!Page.IsPostBack)
{
SqlCommand com = new SqlCommand("select distinct Source from Schedulings", con);
SqlCommand comn=new SqlCommand("select distinct Destination from Schedulings", con);
//SqlDataReader readr;
DropDownList1.DataSource = com.ExecuteReader();
DropDownList1.DataTextField = "Source";
// DropDownList1.DataTextField = "Destination";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "select Source");
con.Close();
con.Open();
DropDownList2.DataSource = comn.ExecuteReader();
DropDownList2.DataTextField = "Destination";
DropDownList2.DataBind();
DropDownList2.Items.Insert(0, "select Destination");
con.Close();
}
//con.Close();
// DropDownList1.DataBind();
//con.Close();
if (IsPostBack)
Label3.Text = "";
//Label1.Visible = false;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// string Source = DropDownList1.SelectedValue.ToString();
// Label1.Text = Source;
}
protected void Button1_Click(object sender, EventArgs e)
{
string src = DropDownList1.SelectedItem.ToString();
string desti = DropDownList2.SelectedItem.ToString();
if ((src == desti) && IsPostBack)
{
Label1.Text = "Source And Destination cant be same!";
}
SqlConnection lop = new SqlConnection("Data Source=KUNDAN-PC\\SQLEXPRESS;Initial Catalog=Ars2.1.2;Integrated Security=True");
lop.Open();
SqlCommand cmd = new SqlCommand("select * from Schedulings where Source=#Source and Destination=#Destination", lop);
cmd.Parameters.AddWithValue("Source", DropDownList1.SelectedItem.Text);
cmd.Parameters.AddWithValue("Destination", DropDownList2.SelectedItem.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count == 0)
{
Label3.Text = "No planes available in this route!!!";
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
I suppose you are refreshing page using F5 or by right clicking on page and opting refresh option or using refresh button of browser. If this is the case then I am scared it's not refresh, it's repeating previous action. That means if you were searching for flight and refreshing using above options, it will again search for flight using same search criteria. You can confirm it by putting debugger on search event. You can avoid this behavior by setting and clearing Session or ViewState and manage label text using it.

Displaying text in texbox from databse based on selected items from combobox

I have basically a combobox and a text box.
The combobox consists of subject code, whereas the textbox consists of a subject name which is stored in the database.
Is there any way that when an item from combobox is selected, it automatically displays the subject name based on the selected subject code, which will be from the database?
Below is my code, but it is not working.
private void Form1_Load(object sender, EventArgs e)
{
con.Open();
OleDbDataAdapter oda1 = new OleDbDataAdapter("select subject_code from subjectinfo", con);
DataTable dt1 = new DataTable();
oda1.Fill(dt1);
comboBoxSubjectCodeUpdate.DataSource = dt1;
comboBoxSubjectCodeUpdate.DisplayMember = "subject_code";
comboBoxSubjectCodeUpdate.SelectedIndex = -1;
con.Close();
}
private void comboBoxSubjectCodeUpdate_SelectedIndexChanged(object sender, EventArgs e)
{
string str = "select subject_abbreviation from subjectinfo where subject_code ='" + comboBoxSubjectCodeUpdate.Text + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["subject_abbreviation"].ToString();//column name should be that you want to show on textbox
}
}

Data not displaying out despite auto-selecting gridview row

I'm trying to let the gridview auto-select the first row of data upon page load. However, in the gridview, it shows that the first row is being highlighted
but no data is being displayed in my textbox. The data only appears when i click the select button in my gridview again.
This is how i added the auto-select gridview row in my page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvnric.SelectedIndex = 0;
}
}
This is how i get my data from my gridview to my textbox
protected void gvnric_SelectedIndexChanged(object sender, EventArgs e)
{
Session["nric"] = gvnric.SelectedRow.Cells[1].Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cm = new SqlCommand("Select fullname, contact, address, email From MemberAccount Where nric = '" + Session["nric"] + "'", con);
SqlDataReader dr;
dr = cm.ExecuteReader();
if (dr.Read())
{
txtFullName.Text = dr["fullname"].ToString();
txtAddress.Text = dr["contact"].ToString();
txtContact.Text = dr["address"].ToString();
txtEmail.Text = dr["email"].ToString();
}
con.Close();
Image1.Attributes["src"] = "MemberNricCard.aspx?";
Image1.Attributes["height"] = "200";
Image1.Attributes["width"] = "200";
}
But what could possibly caused the data not to be displayed when the first row already being selected upon page load.
I would Re Factor the code as below :
PageLoad
if (!IsPostBack)
{
gvnric.SelectedIndex = 0;
LoadFormFields();
}
gvnric_SelectedIndexChanged
protected void gvnric_SelectedIndexChanged(object sender, EventArgs e)
{
LoadFormFields();
}
and create LoadFormFields with what you have in gvnric_SelectedIndexChanged
You can just call your gridview code in the page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvnric.SelectedIndex = 0;
gvnric_SelectedIndexChanged(this, EventArgs.Empty);
}
}

Getting the selected index of drop down list

I am using c# and asp.net in my project.I wanted to get the selectedindex of the dropdownlist but I am getting always as 0.Here is my code of binding the dropdown list with data
MySqlDataReader dr = null;
try
{
//////////////Opening the connection///////////////
mycon.Open();
string str = "select category from lk_category";
MySqlCommand command = mycon.CreateCommand();
command.CommandText = str;
dr = command.ExecuteReader();
DropDownList1.DataSource = dr;
DropDownList1.DataValueField = "category";
DropDownList1.DataBind();
dr.Close();
str = "select technology from lk_technology";
command.CommandText = str;
dr = command.ExecuteReader();
DropDownList2.DataSource = dr;
DropDownList2.DataValueField = "technology";
DropDownList2.DataBind();
}
catch (Exception ex) { Response.Write("Exception reding data" + ex); }
finally
{
//dr.Close();
mycon.Close();
}
And I am trying to get selected index by:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
catID = DropDownList1.SelectedIndex+1;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
techID = DropDownList2.SelectedIndex;
}
Here is my page_load:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["valid"] == null)
Response.Redirect("admin.aspx");
panel1();///If session valid then show panel1;
}
Please tell me where I am going wrong.
That is because you refill the drop down list in page load without checking that it is not post back.
Warping your try-catch (drop down fill) code with
if (!this.IsPostBack)
{
...
}
should solve the problem.

Categories