not working viewstate in asp - c#

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.

Related

How to do OnClick on selected item in "dynamic" ASP.NET DropDownList without using JavaScript

Currently, there is 2 values in my DropDownList which is viewProduct and editProduct. So when the user selects one of the value, it will direct user to the particular function in ASP.NET. I have tried OnSelectedIndexChanged, but it seems like not working on the dynamic DropDownList.
Here is my code:
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
e.Row.Cells[5].Controls.Add(ddlAction);
if(ddlAction.SelectedValue == "editProduct")
{
editProduct();
}
else if(ddlAction.SelectedValue == "viewProduct")
{
retrieveProduct();
}
Any idea how to solve it without using JavaScript?
My entire code:
protected void Page_Load(object sender, EventArgs e)
{
BindGridView();
}
private void BindGridView()
{
MySqlConnection conn = new MySqlConnection(sqlConn);
string sql = "SELECT prodID, prodName, stockLevel, reorderLevel, unitPrice from Product";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
productList.DataSource = dt;
productList.DataBind();
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
TableCell tc = new TableCell();
DropDownList ddlAction = new DropDownList();
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "Prod ID";
e.Row.Cells[1].Text = "Product Name";
e.Row.Cells[2].Text = "Qty";
e.Row.Cells[3].Text = "Reorder Level";
e.Row.Cells[4].Text = "Price (RM)";
e.Row.Controls.Add(tc);
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
var qty = Int16.Parse(e.Row.Cells[2].Text);
var reorder = Int16.Parse(e.Row.Cells[3].Text);
if (qty <= reorder)
{
e.Row.Cells[2].CssClass = "redCell";
e.Row.Cells[3].CssClass = "redCell";
}
e.Row.Controls.Add(tc);
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
e.Row.Cells[5].Controls.Add(ddlAction);
ddlAction.SelectedIndexChanged += DDLAction_OnSelectedIndexChanged;
if (ddlAction.SelectedValue == "editProduct")
{
editProduct();
}
else if (ddlAction.SelectedValue == "viewProduct")
{
retrieveProduct();
}
}
}
You need to declare an event handler then assign it to the control before adding the control to the page.
Here is an example :
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
CreateControl();
}
}
protected void CreateControl()
{
var ddlAction = new DropDownList();
ddlAction.ID = "ddlForAction";
ddlAction.CssClass = "ddlList";
ddlAction.CausesValidation = false;
ddlAction.AutoPostBack = true;
ddlAction.Items.Add(new ListItem("View","viewProduct"));
ddlAction.Items.Add(new ListItem("Edit", "editProduct"));
ddlAction.SelectedIndexChanged += DDLAction_OnSelectedIndexChanged;
e.Row.Cells[5].Controls.Add(ddlAction);
}
protected void DDLAction_OnSelectedIndexChanged(object sender, EventArgs e)
{
var action = (DropDownList) sender;
var choice = action.SelectedValue?.Trim();
string script = null;
switch (choice)
{
case "viewProduct":
script = "alert('View page!');";
break;
case "editProduct":
script = "alert('Edit page!');";
break;
default:
script = "alert('Unmatched Value!')";
break;
}
ScriptManager.RegisterStartupScript(this , typeof(_Default) , "TestJS" , $"<script>{script}</script>" , false);
}
use ScriptManager.RegisterStartupScript when you want to work with JS scripts. Response.Write will not parse script blocks as an executable blocks. It will throw a parse error though (you could check the browser console.

how to set page validation=true for pagination

i have a repeater control for showing products, i want to use pagination for showing some of the products on every page using pagination, but when dataset shows data on first page and i click Next page it shows an error of set page validation=true please help me with this
public partial class WebForm1 : System.Web.UI.Page
{
Database _db = DatabaseFactory.CreateDatabase();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
getdata();
}
else
{
getdata();
}
}
public void getdata()
{
DataSet ds = new DataSet();
DbCommand selectcmd = _db.GetStoredProcCommand("SHOPHIVESP");
ds = _db.ExecuteDataSet(selectcmd);
PagedDataSource Pds1 = new PagedDataSource();
Pds1.DataSource = ds.Tables[0].DefaultView;
Pds1.AllowPaging = true;
Pds1.PageSize = 30;
Pds1.CurrentPageIndex = CurrentPage;
lbl1.Text = "Showing Page: " + (CurrentPage + 1).ToString() + " of " + Pds1.PageCount.ToString();
btnPrevious.Enabled = !Pds1.IsFirstPage;
btnNext.Enabled = !Pds1.IsLastPage;
Repeater1.DataSource = Pds1;
Repeater1.DataBind();
}
public int CurrentPage
{
get
{
object s1 = this.ViewState["CurrentPage"];
if (s1 == null)
{
return 0;
}
else
{
return Convert.ToInt32(s1);
}
}
set { this.ViewState["CurrentPage"] = value; }
}
public void btnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
getdata();
}
public void btnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
getdata();
}
}
please tell me where the problem is, it is the code in c# and just a repeater at front in asp.net help me with this,i am using a stored procedure to select name image price from DB

I am getting one error and I don't know how to fix it

I get an Error on this line of code:
CurrentPage = FillRepeater() – 1;
For paging purpose i use PagedDataSource class, which is the same class used for paging in other databound controls.In FillRepeater() function, I created the object of the PagedDataSource class and used some of its methods.After this simple property used to get the current page value as follows. This simply:
Uses the viewstate to store the current state of the Data page
And also I will add functionality to linkbutton which gets First,
Last, Previous and Next page on click event.
Below is the Code:
public partial class ExamPage : System.Web.UI.Page
{
SqlConnection con;
string query;
public ExamPage()
{
con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
}
private int FillRepeater()
{
query = "select top 10 Question,Option1,Option2,Option3,Option4 from Questions";
SqlCommand cmd = new SqlCommand(query, con);
con.Open(); SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
PagedDataSource pds = new PagedDataSource();
pds.DataSource = ds.Tables[0].DefaultView;
pds.AllowPaging = true; pds.PageSize = 8;
int count = pds.PageCount;
pds.CurrentPageIndex = CurrentPage;
if (pds.Count > 0)
{
lbtnPrev.Visible = true;
lbtnNext.Visible = true;
lbtnFirst.Visible = true;
lbtnLast.Visible = true;
lblStatus.Text = "Page " + Convert.ToString(CurrentPage + 1) + "of" + Convert.ToString(pds.PageCount);
}
else {
lbtnPrev.Visible = false;
lbtnNext.Visible = false;
lbtnFirst.Visible = false;
lbtnLast.Visible = false;
}
lbtnPrev.Enabled = !pds.IsFirstPage;
lbtnNext.Enabled = !pds.IsLastPage;
lbtnFirst.Enabled = !pds.IsFirstPage;
lbtnLast.Enabled = !pds.IsLastPage;
Repeater1.DataSource = pds;
Repeater1.DataBind();
return count;
}
public int CurrentPage
{
get
{
object obj = this.ViewState["_CurrentPage"]; if (obj == null) { return 0; }
else
{
return (int)obj;
}
}
set
{
//set in viewstate the current page number
this.ViewState["_CurrentPage"] = value;
}
}
protected void lbtnPrev_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
FillRepeater();
}
protected void lbtnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
FillRepeater();
}
protected void lbtnFirst_Click(object sender, EventArgs e)
{
CurrentPage = 0;
FillRepeater();
}
protected void lbtnLast_Click(object sender, EventArgs e)
{
CurrentPage = FillRepeater() – 1;
FillRepeater();
}
}
I am getting syntax error not run-time error but I don't know how to solve it. Please tell me where I am making mistake
CurrentPage = FillRepeater() – 1;
In that line, the – character is the en dash. Most programming languages only allow you to use the hyphen-minus, -, to represent subtraction. The hyphen-minus key is present on most keywords.
CurrentPage = FillRepeater() - 1;
The reason why you have an en dash in your code is that it was probably authored using a word processing software, such as Microsoft Word, which automatically converts the hypen-minus to an en dash when the next word is followed by a space.

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"];
{
}

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

Categories