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
Related
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.
I'm trying to get an input as text and save it to SQL table,
the code works fine if the string isn't too long, but when you exceed from about 70 characters the SaveChanges(); command isn't able to save the data.
SQL data type is set to nvarchar(max). Any idea?
private void btnSave_Click(object sender, EventArgs e)
{
Model.TBL_USERS USR = new Model.TBL_USERS();
USR.USR_NAME = txtNAME.Text;
USR.USR_LAST = txtLAST.Text;
USR.USR_MOBILE = txtMOBILE.Text;
USR.USR_TEL1 = txtTEL1.Text ;
USR.USR_ADDRESS = txtADDRESS.Text;
USR.USR_COMPANY = txtCOMPANY.Text;
//USR.USR_COMPANY = "=chrome..69i57.13150j0j4&sourceid=chrome&ie=UTF-8";
DB.TBL_USERS.Add(USR);
DB.SaveChanges();
dataGridView1.DataSource = "";
dataGridView1.DataSource = DB.TBL_USERS.ToList();
}
this is the whole code in the solution :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Model.SAMA_User_CRM_V1 DB = new Model.SAMA_User_CRM_V1();
int IDGRID;
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = DB.TBL_USERS.ToList();
}
private void btnSave_Click(object sender, EventArgs e)
{
Model.TBL_USERS USR = new Model.TBL_USERS();
USR.USR_NAME = txtNAME.Text;
USR.USR_LAST = txtLAST.Text;
USR.USR_MOBILE = txtMOBILE.Text;
USR.USR_TEL1 = txtTEL1.Text ;
USR.USR_ADDRESS = txtADDRESS.Text;
USR.USR_COMPANY = txtCOMPANY.Text;
//USR.USR_COMPANY = "=chrome..69i57.13150j0j4&sourceid=chrome&ie=UTF-8";
DB.TBL_USERS.Add(USR);
DB.SaveChanges();
dataGridView1.DataSource = "";
dataGridView1.DataSource = DB.TBL_USERS.ToList();
}
private void btnDELETE_Click(object sender, EventArgs e)
{
var qdel = DB.TBL_USERS.Where(x => x.ID == IDGRID).ToList();
foreach (var item in qdel)
{
DB.TBL_USERS.Remove(item);
}
DB.SaveChanges();
dataGridView1.DataSource = "";
dataGridView1.DataSource = DB.TBL_USERS.ToList();
}
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{
IDGRID = (int)dataGridView1.Rows[e.RowIndex].Cells["ID"].Value;
}
}
}
considering the comments i found out where the problem is :
initially the model was created with a SQL table that used nvarchar(50) and after changing that to nvarchar(500) or nvarchar(max) the model.edmx needed to be updated ... after updating the model all things worked like a charm .
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();
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.
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.