Getting the selected index of drop down list - c#

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.

Related

Get value of the third column in a table in selectedindex changed event of dropdown list in asp.net

This is my code to display table value to a DropDownList.
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString))
{
con.Open();
string str="SELECT ItemOne,ItemTwo,ItemThree FROM tableItem";
using (SqlCommand cmd = new SqlCommand(str, con))
{
SqlDataAdapter dA=new SqlDataAdapter(cmd);
dA.Fill(dT);
DropDownList1.DataSource = dT;
DropDownList1.DataValueField = "ItemTwo";
DropDownList1.DataTextField = "ItemOne";
DropDownList1.DataBind();
}
This is to display the selected value of DropDownList to a TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = //Get the value of ItemThree here
}
My problem is: How will I display the column value of ItemThree in another TextBox.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropDownList1.Items[2].ToString(); // 2 is your index
}
Another way of doing this
var connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
var sql = "SELECT ItemOne, ItemTwo, ItemThree FROM tableItem";
using (var table = new DataTable) {
using (var adapter = new SqlDataAdapter(sql, connectionString)
adapter.Fill(table);
foreach (DataRow dr in table.Rows)
DropDownList1.Items.Add(new ListItem(dr["ItemTwo"], dr["ItemTwo"]) {
Tag = dr["ItemThree"]
});
}
Then from the event handler
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedValue.ToString();
TextBox2.Text = DropdownList1.SelectedItem.Tag.ToString();
}

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.

search, edit and delete using gridview with sql server in c#

i am using Gridview buttons to edit and delet records from sql DB , the problem that i use specific criteris (search by textbox and combobox) then i do edit for the results here is the code i use :
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["zamzammembersConnectionString"].ConnectionString);
if (!IsPostBack)
{
bind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbl = (Label)row.FindControl("lblid");
TextBox textname = (TextBox)row.FindControl("textbox1");
TextBox textmarks = (TextBox)row.FindControl("textbox2");
GridView1.EditIndex = -1;
conn.Open();
SqlCommand cmd = new SqlCommand("update emp set marks=" + textmarks.Text + " , name='" + textname.Text + "' where rowid=" + lbl.Text + "", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();
}
public void bind()
{
conn.Open();
SqlCommand com = new SqlCommand("select zam_pcinfo.employe_name as Name , zam_location.locationname as Location from zam_pcinfo inner join zam_location on zam_pcinfo.location_id = zam_location.locationId where zam_pcinfo.employe_name like #name or zam_location.locationname like #locationname;", conn);
com.Parameters.AddWithValue("#name", SqlDbType.VarChar).Value = nametxt.Text;
com.Parameters.AddWithValue("#locationname", SqlDbType.VarChar).Value = locationdrop.SelectedValue;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbldeleteID = (Label)row.FindControl("lblid");
conn.Open();
SqlCommand cmd = new SqlCommand("delete emp where rowid=" + lbldeleteID.Text + "", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bind();
}
}
when i try to make the same code in bind() method to a button it works fine but i couldn't do edit and delete on it . how can i make edit and delete in gridview with data that i search for ?

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);
}
}

ASP.NET DetailsView custom forward only paging

In my aspx page I have a DetailsView and a SqlDataSource and a button labeled "Next".
The datasource mode has been set to DataReader since i only need to advance forward.
In my cs page, I have:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("PickRandomQuestions", conn);
comm.CommandType = System.Data.CommandType.StoredProcedure;
comm.Parameters.Add("QuizID", SqlDbType.Int);
comm.Parameters["QuizID"].Value = 1;
conn.Open();
reader = comm.ExecuteReader();
QuestionDetails.DataSource = reader;
QuestionDetails.DataBind();
}
}
protected void ButtonNext_Click(object sender, EventArgs e)
{
if (reader.Read())
{
QuestionDetails.DataSource = reader;
QuestionDetails.DataBind();
}
else
{
conn.Close();
reader.Close();
}
}
Now when i click on the Next button, i get System.NullReferenceException: Object reference not set to an instance of an object.
What am i doing wrong?

Categories