when i press the button the application gives me an error "index out of range" [closed] - asp.net

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
In this code I dynamically create checkboxes which I populate with data from my database.
My intention is when I press the btnProba button to show the text property only from the selected checkboxes. But it gives me an error in this row saying that index is out of range! I can't explain why.
lblProba.Text = myche[0];
public partial class FormEGN : System.Web.UI.Page
{
string mynewstring;
List<string> myche = new List<string>();
CheckBoxList mycheckbox = new CheckBoxList();
protected void Page_Load(object sender, EventArgs e)
{
mynewstring = (string)Session["id2"];
// lblProba.Text = mynewstring;
if(!IsPostBack)
{
ddlNumberTourists.Items.Add("1");
ddlNumberTourists.Items.Add("2");
ddlNumberTourists.Items.Add("3");
}
}
protected void ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e)
{
int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
Label myLabel = new Label();
myLabel.ID = "lblAccomodation" + (i + 1).ToString();
myLabel.Text = "Настаняване Турист" + (i + 1).ToString();
Page.FindControl("form1").Controls.Add(myLabel);
DropDownList myDropDownList = new DropDownList();
myDropDownList.ID = "ddlTourist" + i.ToString();
Page.FindControl("form1").Controls.Add(myDropDownList);
Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
string connectionString = "Server=localhost\\SQLEXPRESS;Database=EXCURSIONSDATABASE;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
// CheckBox myCheckbox = new CheckBox();
// myCheckbox.ID = "ckbExtraCharge" + i.ToString() + s.ToString();
// myCheckbox.Text = rd["Extra_Charge_Description"].ToString();
// Page.FindControl("form1").Controls.Add(myCheckbox);
// Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
// s++;
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Items.Add(rd["Extra_Charge_Description"].ToString());
Page.FindControl("form1").Controls.Add(mycheckbox);
if (mycheckbox.Items[s].Selected == true)
{
myche.Add(mycheckbox.Items[s].Text);
}
s++;
}
}
catch (Exception ex)
{ }
}
}
protected void btnProba_Click(object sender, EventArgs e)
{
lblProba.Text = myche[0];
}
protected void btnReserve_Click(object sender, EventArgs e)
{
string num = Request.QueryString["ExcursionID"];
Response.Redirect(String.Format("ClintsInformation.aspx?Excursiondate_ID={0}",num));
}
}
}

The function ddlNumberTourists_SelectedIndexChanged is the one that set the myche when is find some selected, but the data is lost on the second call where is the
protected void btnProba_Click(object sender, EventArgs e)
{
// here is the issue
lblProba.Text = myche[0];
}
The two calls are happening on different post back.
You need to call the ddlNumberTourists_SelectedIndexChanged(object sender, EventArgs e) on button click and not on every change of the dropdownlist, eg I rename it to CheckWhatIsSelected() and here is the code:
protected void CheckWhatIsSelected()
{
int numTourists = Convert.ToInt32(ddlNumberTourists.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
Label myLabel = new Label();
myLabel.ID = "lblAccomodation" + (i + 1).ToString();
myLabel.Text = "??????????? ??????" + (i + 1).ToString();
Page.FindControl("form1").Controls.Add(myLabel);
DropDownList myDropDownList = new DropDownList();
myDropDownList.ID = "ddlTourist" + i.ToString();
Page.FindControl("form1").Controls.Add(myDropDownList);
Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
string connectionString = "Server=localhost\\SQLEXPRESS;Database=EXCURSIONSDATABASE;Trusted_Connection=true";
string query =
"SELECT Extra_Charge_ID, Excursion_ID, Amout, Extra_Charge_Description FROM EXTRA_CHARGES WHERE Excursion_ID=" + mynewstring;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
try
{
conn.Open();
SqlDataReader rd = cmd.ExecuteReader();
int s = 0;
while (rd.Read())
{
// CheckBox myCheckbox = new CheckBox();
// myCheckbox.ID = "ckbExtraCharge" + i.ToString() + s.ToString();
// myCheckbox.Text = rd["Extra_Charge_Description"].ToString();
// Page.FindControl("form1").Controls.Add(myCheckbox);
// Page.FindControl("form1").Controls.Add(new LiteralControl("<br />"));
// s++;
mycheckbox.ID = "chkblextracharge" + i.ToString() + s.ToString();
mycheckbox.Items.Add(rd["Extra_Charge_Description"].ToString());
Page.FindControl("form1").Controls.Add(mycheckbox);
if (mycheckbox.Items[s].Selected == true)
{
myche.Add(mycheckbox.Items[s].Text);
}
s++;
}
}
catch (Exception ex)
{ }
}
}
protected void btnProba_Click(object sender, EventArgs e)
{
CheckWhatIsSelected();
if(myche.Count > 0)
lblProba.Text = myche[0];
else
lblProba.Text = "Non selected";
}
One other possible solution is to save the myche on viewstate.

Other solution using the ViewState. You use the ViewState to store your selection and you have it after the post back. Do not forget to clear your list on ddlNumberTourists_SelectedIndexChanged
List<string> myche
{
get
{
if (!(ViewState["cMyChe"] is List<string>))
{
// need to fix the memory and added to viewstate
ViewState["cMyChe"] = new List<string>();
}
return (List<string>)ViewState["cMyChe"];
}
}
protected void btnProba_Click(object sender, EventArgs e)
{
// double check if have something on the list
if(myche.Count > 0)
lblProba.Text = myche[0];
else
lblProba.Text = "Non selected";
}

Related

Grid View only updates when page refresh

In my application i have a grid view and a save task button. when i click save task my button , the Grid View doesn't refresh but when i click the refresh button of browser the grid refreshes and automatically add another task in the database. All i want is to refresh the grid when save task button is click and not add task when browser refresh button is clicked.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Default2 : System.Web.UI.Page
{
static string startdate;
DataTable dt;
static string enddate;
static string EstDate;
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
protected void Page_Load(object sender, EventArgs e)
{//Page dosn't go back//
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetNoStore();
if (IsPostBack)
{
if (Session["auth"] != "ok" )
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
//Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
else
{
GridView1.DataSource = dt;
GridView1.DataBind();
if (Session["auth"] != "ok")
{
Response.Redirect("~/Login.aspx");
}
else if (Session["desg"] != "Scrum Master")
{
// Response.Redirect("~/errorpage.aspx");
addtaskbtnPannel.Visible = false;
}
}
//decode url data in query string
labelID.Text = HttpUtility.UrlDecode(Request.QueryString["Id"]);
labelDur.Text = HttpUtility.UrlDecode(Request.QueryString["Duration"]);
labelStatus.Text = HttpUtility.UrlDecode(Request.QueryString["Status"]);
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
if (!IsPostBack)
{
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
}
protected void saveTask_Click(object sender, EventArgs e)
{
string str = #"Data Source=ALLAH_IS_GREAT\sqlexpress; Initial Catalog = Task_Manager; Integrated Security = true";
try
{
String query = "insert into Tasks (T_Description, T_Status,S_ID,StartDate,EstEndDate) values('" + TaskDesBox.Text + "', 'incomplete','" + labelID.Text + "' ,'" + startdate + "','" + EstDate + "');";
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
GridView1.DataBind();
}
else
{
TaskStatus.Text = "Task not Saved";
}
}
catch (Exception ex)
{
Response.Write("reeor" + ex);
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void TaskDesBox_TextChanged(object sender, EventArgs e)
{
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Calendar1.Visible = true;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
startdate = Calendar1.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
SDate.Text = startdate;
Calendar1.Visible = false;
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Calendar2.Visible = true;
}
protected void Calendar2_SelectionChanged(object sender, EventArgs e)
{
EstDate = Calendar2.SelectedDate.ToString("yyyy-MM-dd hh:mm:ss");
EstDateBox.Text = EstDate;
Calendar2.Visible = false;
}
}
What you are doing on a post back is:
First show the results due to code in your Page_Load
Then perform event handlers, so if you pushed the Save button, the saveTask_Click will be performed, which adds a record to the database. You don't update your grid view datasource, but just call DataBind() afterwards which still binds the original DataSource.
Imo you shouldn't update your grid view on Page_Load. You should only show it initially on the GET (!IsPostBack).
And at the end of saveTask_Click you have to update your grid view again.
So move the code you need to show the grid view to a method you can call on other occasions:
protected void ShowGridView() {
String pId = HttpUtility.UrlDecode(Request.QueryString["pID"]);
string query = "Select * from Tasks where S_ID=" + labelID.Text;
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand(query, con);
con.Open();
SqlDataReader sdr = null;
sdr = com.ExecuteReader();
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id"), new DataColumn("Description"), new DataColumn("Status"), new DataColumn("Sprint_ID"), new DataColumn("pID") });
while (sdr.Read())
{
dt.Rows.Add(sdr["T_ID"].ToString(), sdr["T_Description"].ToString(), sdr["T_Status"].ToString(), labelID.Text,pId);
}
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
Then call it in your Page_Load on !IsPostBack
if (!IsPostBack)
{
ShowGridView();
PanelTaskForm.Visible = false;
Panel1.Visible = false;
}
else if(IsPostBack){
PanelTaskForm.Visible = true;
Panel1.Visible = true;
}
Then after adding the row in saveTask_Click you can call ShowGridView() to see the new result.
if (com.ExecuteNonQuery() == 1)
{
TaskStatus.Text = "Task Successfully Saved ";
//GridView1.DataBind();
ShowGridView();
}
else
{
TaskStatus.Text = "Task not Saved";
}

dropdownlist index changed value

I have a problem when I change dropdownlist1 item, The changed item not being accessed on the event of DropDownList1_SelectedIndexChanged.
Here is my code...
namespace My_News.Views.Shared
{
public partial class Master : System.Web.UI.MasterPage
{
SqlDataReader dr;
string user_id = "";
protected void Page_Load(object sender, EventArgs e)
{
/* user login information */
if (Session["status"] != null)
{
Button1.Text = "Logout";
Button2.Visible = true; ;
Button2.Text = Session["name"] as string + "'s Profile";
Button3.Enabled = true;
DropDownList1.Enabled = true;
user_id = Session["reg_id"] as string;
DropDownList1.Items.Clear();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection_String"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT DISTINCT[news_category] from [news_profile] WHERE [user_id]='" + user_id + "'";
cmd.Connection = connection;
connection.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
DropDownList1.Items.Add(dr[0].ToString());
}
connection.Close();
}
}
}
else
{
Button1.Text = "Login";
Button2.Visible = false;
Button3.Enabled = false;
DropDownList1.Enabled = false;
Session.Clear();
}
}
Dropdownnlist index change event...
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["news_category"] = DropDownList1.Text;
Session["reload"] = "yes";
Session.Timeout = 10;
Response.Redirect("Default.aspx");
}
}
}
Please help me.
You need to modify your code like this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindDDL();
}
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
string s = ddl.Text;
}
public void bindDDL()
{
DataTable dt = new DataTable("Drop");
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "ABCD");
dt.Rows.Add(2, "EFGH");
ddl.DataSource = dt;
ddl.DataValueField = "ID";
ddl.DataTextField = "Name";
ddl.DataBind();
}

ASP.NET, Code on click of a next button

The following is my code, I am doing project on online examination in that I have a module of question to display in this when I click on next button it should go to the next question but it is not going.
public partial class Student : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
int i=1;
Session["Number"] = i;
protected void Page_Load(object sender, EventArgs e)
{
Session["Number"] = i++;
Label1.Text = Session["Number"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Questions where QuestionNo = '"+Label1.Text+"'", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Label2.Text = dr["Question"].ToString();
Label3.Text = dr["Ans1"].ToString();
Label4.Text = dr["Ans2"].ToString();
Label5.Text = dr["Ans3"].ToString();
Label6.Text = dr["Ans4"].ToString();
}
con.Close();
con.Open();
SqlCommand cmd1 = new SqlCommand("Select * from Answers where QuestionNo = '" + Label1.Text + "'", con);
SqlDataReader dr1 = cmd1.ExecuteReader();
if (dr1.Read())
{
Label8.Text = dr1["Answer"].ToString();
}
con.Close();
}
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton1.Checked)
{
Label7.Text = Label3.Text;
}
}
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
Label7.Text = Label4.Text;
}
}
protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton3.Checked)
{
Label7.Text = Label5.Text;
}
}
protected void RadioButton4_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton4.Checked)
{
Label7.Text = Label6.Text;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Label7.Text == Label8.Text)
{
Label9.Text = "Your Answer is correct";
}
else
Label9.Text = "Your Answer is incorrect";
}
protected void Button2_Click(object sender, EventArgs e)
{
i++;
Session["Number"] = i;
Response.Redirect("Student.aspx");
}
}
So many bad things in this code.
You should always give names to your variables properly.
Don't concatenate SQL queries because security reasons like SQL Injection
You should use Session["Number"] to select the question number rather than Label1.Text.
Use session when it was only necessary.
First thing that you are doing wrong is how you are trying to store value of i in your Session. You are overwriting it every time you get into the method and thus resulting in same question number on each button click.
Second, you should parametrized your queries.
On each button click you should retrieve the value of i from your session and then increment it and again store it in the session. like:
int i = 0;
if (Session["Number"] == null)
{
Session["Number"] = i;
}
else
{
i = Convert.ToInt32(Session["Number"]);
}
//Later To increment Session
Session["Number"] = ++i; //First increments, then assigns the value
You should also use ++i instead of i++ since that will store the value of i before increment.

Unable to serialize the session state

i am tired wondering the issue for this problem. have read so many blogs and forums for this but i am not able to find out the problem.
I am using "SQLServer" mode to store session.
Everything is working fine. But whenever i use search function in my website, it throws the below error:
"Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode."
I am assuming that this is because of the paging code i have used on that page. That code is as below:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select xxxxqueryxxxx";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
try
{
using (con)
{
con.Open();
da.Fill(ds);
}
}
catch
{
ds = null;
}
finally
{
if (ds != null)
{
CustomPaging page = new CustomPaging();
DataTable dt = ds.Tables[0];
page.PageSize = 10;
page.DataSource = dt;
page.CurrentPageIndex = 0;
no = 1;
Session["DT"] = dt;
Session["page"] = page;
bindData(page, dt);
//set these properties for multi columns in datalist
DataList2.RepeatColumns = 1;
DataList2.RepeatDirection = RepeatDirection.Horizontal;
}
}
}
}
void bindData(CustomPaging page, DataTable dt)
{
try
{
DataList2.DataSource = page.DoPaging;
DataList2.DataBind();
//DataList2.DataSource = SqlDataSource1;
//DataList2.DataBind();
lbtnPre.Enabled = !page.IsFirstPage; //Enable / Disable Navigation Button
// lbtnPre.CssClass = "disabledbtn";
lbtnNext.Enabled = !page.IsLastPage;
//lbtnNext.CssClass = "disabledbtn";
lblStatus.Text = NavigationIndicator(); //Build Navigation Indicator
//for creating page index
DataTable dt1 = new DataTable();
dt1.Columns.Add("PageIndex");
dt1.Columns.Add("PageText");
for (int i = 0; i < page.PageCount; i++)
{
DataRow dr = dt1.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt1.Rows.Add(dr);
}
dlPaging.DataSource = dt1;
dlPaging.DataBind();
dlPaging.RepeatColumns = 10;
dlPaging.RepeatDirection = RepeatDirection.Horizontal;
}
catch (Exception)
{
}
finally
{
page = null;
}
}
string NavigationIndicator()
{
string str = string.Empty; //Page x Of Y
str = Convert.ToString(((CustomPaging)Session["page"]).CurrentPageIndex + 1) + " of " + ((CustomPaging)Session["PAGE"]).PageCount.ToString() + " Page(s) found";
return str;
}
protected void lbtnPre_Click(object sender, EventArgs e)
{
int pageIndex = ((CustomPaging)Session["page"]).CurrentPageIndex;
if (!((CustomPaging)Session["page"]).IsFirstPage)
//Decrements the pageIndex by 1 (Move to Previous page)
((CustomPaging)Session["page"]).CurrentPageIndex -= 1;
else
((CustomPaging)Session["page"]).CurrentPageIndex = pageIndex;
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
protected void lbtnNext_Click(object sender, EventArgs e)
{
int pageIndex = ((CustomPaging)Session["page"]).CurrentPageIndex;
if (!((CustomPaging)Session["page"]).IsLastPage)
//Increments the pageIndex by 1 (Move to Next page)
((CustomPaging)Session["page"]).CurrentPageIndex += 1;
else
((CustomPaging)Session["page"]).CurrentPageIndex = pageIndex;
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
protected void DataList2_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx?partnumber=" + DataList2.DataKeyField[DataList2.SelectedIndex].ToString());
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Select")
{
no = int.Parse(e.CommandArgument.ToString()) + 1;
((CustomPaging)Session["page"]).CurrentPageIndex = int.Parse(e.CommandArgument.ToString());
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
}
protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton btn = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (btn.Text == no.ToString())
{
btn.ForeColor = System.Drawing.Color.Maroon;
btn.Font.Underline = false;
}
else
{
btn.ForeColor = System.Drawing.Color.DarkCyan;
btn.Font.Underline = false;
}
}
I just want to know what the problem is in the coding and "how to serialize the session"?
What shold i do to improve the coding?
Any help will be appreciated.
Thank You
I guess your custom paging control is not serializable. This must be the cause of the issue.
Anyway, storing a control in session is not a good idea. Just store the few serializable properties which enable to rebuild the control (PageSize and CurrentPageIndex), or pass them in query string for example.
You could also use ViewState if you can
About storing the DataTable in Session, this might be a really bad idea if you have a lot of data and many connected users.

update cancel on gridview asp.net

I am trying to update a gridview on asp.net using a stored procedure but it always resets to the original values. What am I doing wrong?
edit: all page code added now
protected void page_PreInit(object sender, EventArgs e)
{
MembershipUser UserName;
try
{
if (User.Identity.IsAuthenticated)
{
// Set theme in preInit event
UserName = Membership.GetUser(User.Identity.Name);
Session["UserName"] = UserName;
}
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
//to edit grid view
protected void GridViewED_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewED.EditIndex = e.NewEditIndex;
}
protected void GridViewED_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_UpdateRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
command.Parameters.Add("#PostalAddress", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[0].Controls[0]).Text;
command.Parameters.Add("#TelephoneNo", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
command.Parameters.Add("#Website", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
command.Parameters.Add("#Email", SqlDbType.VarChar).Value = ((TextBox)GridViewED.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
}
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
command.ExecuteNonQuery();
MyConnection.Close();
GridViewED.EditIndex = -1;
}
I suspect the code loading the grid is being invoked upon postback, which is causing the data to be pulled from the database when you don't want it to.
Yes - I think you want the code to only load if it is not a postback. You can use the Page.IsPostBack property for this.
Something like this:
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = Session["UserName"].ToString();
if (!IsPostBack) {
SqlDataReader myDataReader = default(SqlDataReader);
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RescueAnimalsIrelandConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand("sp_EditRescueDetails", MyConnection);
if (!User.Identity.IsAuthenticated)
{
}
else
{
command.Parameters.AddWithValue("#UserName", userLabel.Text.Trim());
}
try
{
command.CommandType = CommandType.StoredProcedure;
MyConnection.Open();
myDataReader = command.ExecuteReader(CommandBehavior.CloseConnection);
// myDataReader.Read();
GridViewED.DataSource = myDataReader;
GridViewED.DataBind();
if (GridViewED.Rows.Count >= 1)
{
GridViewED.Visible = true;
lblMsg.Visible = false;
}
else if (GridViewED.Rows.Count < 1)
{
GridViewED.Visible = false;
lblMsg.Text = "Your search criteria returned no results.";
lblMsg.Visible = true;
}
MyConnection.Close();
}
catch (SqlException SQLexc)
{
Response.Write("Read Failed : " + SQLexc.ToString());
}
}
}
Don't bind your data in the Page_Load event. Create a separate method that does it, then in the Page Load, if !IsPostback, call it.
The reason to perform the databinding is it's own method is because you'll need to call it if you're paging through the dataset, deleting, updating, etc, after you perform the task. A call to a method is better than many instances of the same, repetitive, databinding code.

Resources