Data not displaying out despite auto-selecting gridview row - c#

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

Related

Populate gridview from dropdown control (C#)

I worked on asp web page that have a dropdown of semester names, and according to the selected item from this dropdown a gridview of levels and courses will appear.
The problem is that grid view never change according to the drop down selection
So when i choose a semester name let's say "Fall", the gridview shows all semesters " Fall & Spring & Summer" with their levels and courses.
Here is my code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvSemester.DataSource = GetData(string.Format("select COURSE_SEMESTER from COURSE GROUP BY COURSE_SEMESTER"));
gvSemester.DataBind();
}
}
private static DataTable GetData(string query)
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
using (OracleConnection con = new OracleConnection(constr))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.CommandText = query;
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
protected void Show_Hide_LevelsGrid(object sender, EventArgs e)
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("pnlLevels").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/image/minus.png";
string semesterId = gvSemester.DataKeys[row.RowIndex].Value.ToString();// semester
GridView gvLevel = row.FindControl("gvLevel") as GridView;
BindLevels(semesterId, gvLevel);
}
else
{
row.FindControl("pnlLevels").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/image/plus.png";
}
}
private void BindLevels(string semesterId, GridView gvLevel)
{
gvLevel.ToolTip = semesterId;
gvLevel.DataSource = GetData(string.Format("SELECT COURSE_LEVEL from COURSE where COURSE_SEMESTER= '" + semesterId + "' GROUP BY COURSE_LEVEL ORDER BY COURSE_LEVEL")); //was COURSE_SEMESTER=Check it shows the selected semester levels for all
gvLevel.DataBind();
}
protected void Show_Hide_CoursesGrid(object sender, EventArgs e)
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
row.FindControl("pnlCourses").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "~/image/minus.png";
string levelId = (row.NamingContainer as GridView).DataKeys[row.RowIndex].Value.ToString();//level
GridView gvCourse = row.FindControl("gvCourse") as GridView;//..
BindCourses(levelId, gvCourse);//..
}
else
{
row.FindControl("pnlCourses").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "~/image/plus.png";
}
}
private void BindCourses(string levelId, GridView gvCourse)
{
gvCourse.ToolTip = levelId;
gvCourse.DataSource = GetData(string.Format("select * from COURSE where COURSE_LEVEL='{0}'", levelId));
gvCourse.DataBind();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
You can set your dropdown list AutoPostBack = True.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
BindLevels();
}
fill your gridview with dropdown SelectedIndexChanged event and apply where condition in your SQL query.
Add Update Panel for the "levels and courses" grid.
At the dropdown Change event , you update the grid.
UpdatePanelId.Update();

DropDownList Clear Selection in C# ASP.Net

I have listed employee names in one Dropdownlist. And by selecting any employee i am displaying employee details in gridview from database.
By default, dropdownlist have first item as selected item.So when i select another items it returns the first index only.
My Code:
protected void FilterBtn_Click(object sender, EventArgs e)
{
if (EmployeeList.SelectedIndex > -1)
{
sInitQuery = sInitQuery + " WHERE (EmployeeName ='" + EmployeeList.SelectedItem.ToString() + "')";
}
if (GlobalCS.OpenConnection() == true)
{
GridView1.DataSource = null;
GridView1.DataBind();
MySqlCommand cmd = new MySqlCommand(sInitQuery, GlobalCS.objMyCon);
MySqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Close();
}
GlobalCS.CloseConnection();
EmployeeList.ClearSelection();
}
Put your page load code in if condition so it is just executed first time when page is loaded, other wise whenever post back happens page load gets called and your code will get executed which is the reason it gets set to first item everytime:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
DisplayDatainGrid(); //All data in GridView
AddDataDropList(); //Load data in Dropdownlist
}
}
Currently every time your pageload code is exxecuting which should not happen.
Add EmployeeList.SelectedIndex to the ViewState.
protected void EmployeeList_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState.Add("employeeListIndex", EmployeeList.SelectedIndex);
}
Then, in Page_Load, read the ViewState and assign the value to EmployeeList.SelectedIndex.
void Page_Load(object sender, EventArgs e)
{
if(ViewState["employeeListIndex"] != null)
{
EmployeeList.SelectedIndex = ViewState["employeeListIndex"];
{
}

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 ?

not working viewstate in asp

In my ASP.NET Web Application, I have a "Next" button control. Each time I click this button, I want the value of ViewState["QNO"] to increase by 1.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int qno = Convert.ToInt32(ViewState["QNO"]);
if (ViewState["QNO"] == null)
{
ViewState["QNO"] = 1;
}
else
{
ViewState["QNO"] = qno++;
}
}
Code for click event on button:
protected void btnNext_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(str);
con.Open();
SqlCommand cmd = new SqlCommand("select * from QSet where QID='" + ViewState["QNO"] + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
lblNo.Text = "(" + dr.GetValue(0).ToString() + ")";
lblQues.Text = dr.GetValue(1).ToString();
Qoptions.Items.Add(dr.GetValue(2).ToString());
Qoptions.Items.Add(dr.GetValue(3).ToString());
Qoptions.Items.Add(dr.GetValue(4).ToString());
Qoptions.Items.Add(dr.GetValue(5).ToString());
}
con.Close();
}
Change your code for Page Load as this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["QNO"] = 1;
}
else
{
ViewState["QNO"] = Convert.ToInt32(ViewState["QNO"]) +1;
}
}
I believe a server side button click causes a PostBack. In your code, you have if (!IsPostBack) then increment by 1. Change to if (IsPostBack) perhaps.
code inside if (!IsPostBack) will only be hit on initial load.
change load code to
if (IsPostBack)
{
if (ViewState["QNO"] == null)
{
ViewState["QNO"] = 1;
}
else
{
int qno = Convert.ToInt32(ViewState["QNO"]);
ViewState["QNO"] = qno++;
}
}
The problem is with the assignment of the increment operator. Also, I made few corrections.
public void IncrementQNO()
{
if (ViewState["QNO"] == null)
{
ViewState["QNO"] = 1;
}
else
{
int qno = Convert.ToInt32(ViewState["QNO"]);
ViewState["QNO"] = ++qno;
}
}
protected void Page_Load(object sender, EventArgs e)
{
IncrementQNO();
}
Just tested this and it works fine.
In your page_load, this line will fail right away:
int qno = Convert.ToInt32(ViewState["QNO"]);
The code is not running in a postback, so anything you pull out of viewstate will, by definition, be null.
You need another code path to initialize "QNO" with 0 if not in postback.

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