Retain textbox values while Gridview Paging - asp.net

On page index i am not able to hold the given value in the TextBox ,i have tried different logics but nothing is giving a correct result
here is Code
protected void gvViolationCodes_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
RememberOldValues();
//to rebind the data based on changed page index
violationCodePresenter.GetViolationCodesList(Convert.ToInt32(ddlStatus.SelectedValue), Convert.ToInt32(Session["LanguageID"]));
gvViolationCodes.PageIndex = e.NewPageIndex;
gvViolationCodes.DataBind();
RePopulateValues();
}
and the Method to store previous values is as follows
private void RememberOldValues()
{
DataTable dt = new DataTable();
dt.Columns.Add("row_index");
dt.Columns.Add("edited_value");
foreach (GridViewRow gvr in gvViolationCodes.Rows)
{
TextBox tb = (TextBox)gvr.FindControl("txtSeqNo");
HiddenField hf = (HiddenField)gvr.FindControl("HiddenField1");
if (tb.Text != hf.Value)
{
DataRow dr = dt.NewRow();
dr["row_index"] = gvr.RowIndex;
dr["edited_value"] = tb.Text;
dt.Rows.Add(dr);
}
}
if (dt.Rows.Count == 0 && Session["retain"] == null && Session["page-index"] == null)
{
Session["retain"] = null;
Session["page-index"] = null;
}
else if (dt.Rows.Count > 0 && Session["retain"] == null && Session["page-index"] == null)
{
Session["retain"] = dt;
Session["page_index"] = gvViolationCodes.PageIndex;
}
else if (Session["retain"] == null && Session["page-index"] == null)
{
Session["retain"] = dt;
Session["page_index"] = gvViolationCodes.PageIndex;
}
}

Use ViewState object to hold textbox values across page postback which is occurring because of paging in gridview.

Related

Gridview not populating by datatable

Below is the code where The four columns("Challan Number","Proposal Number","CTS Number" and "Amount") is obtained from Sql-Database, and the ("Land" and "Ward") values are obtained from respective methods. The values obtaines are correct but still the "ChallanGridview" is not getting populated.
The datarow "dr1" gets populated with the correct required values, but the "ChallanGridview" doesn't shows anything.
public void FillChallanGrid()
{
string query = string.Empty;
string cs = ConfigurationManager.ConnectionStrings["ConStrg"].ConnectionString;
query = CtrlChallenSearch1.GetChallanQuery();
using(SqlConnection con=new SqlConnection(cs))
{
SqlDataAdapter da = new SqlDataAdapter(query,con);
DataSet ds = new DataSet();
da.Fill(ds,"entry");
int x = ds.Tables["entry"].Rows.Count;
DataTable dt = new DataTable();
dt.Columns.Add("Challan Number");
dt.Columns.Add("Proposal Number");
dt.Columns.Add("CTS Number");
dt.Columns.Add("Amount");
dt.Columns.Add("Land");
dt.Columns.Add("Ward");
for(int i=0;i<x;i++)
{
DataRow dr = ds.Tables["entry"].Rows[i];
DataRow dr1 = dt.NewRow();
dr1["Challan Number"] = dr["ReceiptNo"].ToString();
dr1["Proposal Number"] = dr["ProposalNo"].ToString();
dr1["CTS Number"] = dr["CTSNo"].ToString();
dr1["Amount"] = dr["Amount"].ToString();
dr1["Land"] = GetLand(dr["ProposalNo"].ToString());
dr1["Ward"]=GetWard(dr["ProposalNo"].ToString());
dt.Rows.Add(dr1);
}
ChallanGridView.DataSource = dt;
ChallanGridView.DataBind();
}
}
private object GetLand(string ProposalNumber)
{
string retvalue = string.Empty;
if (ProposalNumber != "" || ProposalNumber != null || ProposalNumber != string.Empty)
{
string[] splittedvalue = ProposalNumber.Split('/');
retvalue = splittedvalue[1];
}
return retvalue;
}
private object GetWard(string ProposalNumber)
{
string retvalue = string.Empty;
string[] splittedvalue = new string[3];
splittedvalue = ProposalNumber.Split('/');
retvalue = splittedvalue[0];
return retvalue;
}
protected void Button1_Click(object sender, EventArgs e)
{
FillChallanGrid();
}
Its solved, I just deleted the present gridview and added another fresh one,
don't know how and why, but the error was gone.
btw thnks Asif.Ali!

How to count the no of records in gridview which have some particular data in a coloumn

How to count the no of records in Gridview which have some particular data in a column
name result
======== ======
krishna pass
sanjay pass
ajay fail
out put needed in grid view - above Gridview already present,according to that grid i have to make another grid to count results
result no
====== =====
pass 2
fail 1
in data row bound , i calculated
protected void GVKeywordReport_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow pr = ((DataRowView)e.Row.DataItem).Row;
int oldPos = Convert.ToInt32(pr["oldposition"]);
int newPos = Convert.ToInt32(pr["newposition"]);
GVKeywordReport.HeaderRow.Cells[3].Text = txtfrmdate.Text;
GVKeywordReport.HeaderRow.Cells[4].Text = txtEndDate.Text;
GVKeywordReport.HeaderRow.BackColor = ColorTranslator.FromHtml("#B3B300");
e.Row.Cells[0].BackColor = ColorTranslator.FromHtml("#B3B300");
e.Row.Cells[5].BackColor = ColorTranslator.FromHtml("#FFFFFF");
if (oldPos == newPos)
{
e.Row.BackColor = ColorTranslator.FromHtml("#FF950E");
e.Row.Cells[6].Text = "No Change";
nc= nc+1;
}
else if (oldPos > newPos)
{
e.Row.BackColor = ColorTranslator.FromHtml("#FFFFCC");
e.Row.Cells[6].Text = "Improved";
imprv= imprv+1;
}
else
{
e.Row.BackColor = ColorTranslator.FromHtml("#FF0000");
e.Row.Cells[6].Text = "Decreased";
decrs=decrs+1;
}
// e.Row.Cells[0].BackColor = ColorTranslator.FromHtml("#7DA647");
}
txt_TargetReached.Text = "0";
txtDecreased.Text =Convert.ToString(decrs);

How to sort ASPxGridView column nulls last?

My dataset contains null values and - by default - null values ​​come first.
When sorting the data, how do I get null values ​​last?
Handle the OnColumnSort event for your ASPxGridView as below:
protected void myGrid_CustomColumnSort(object sender, CustomColumnSortEventArgs e)
{
if (e.Column == null)
return;
if (!e.Column.FieldName.ToString().Equals("myColumnFieldName"))
return;
if (e.Value1 == DBNull.Value || e.Value1 == null)
e.Result = 1;
else
if (e.Value2 == DBNull.Value || e.Value2 == null)
e.Result = -1;
else
e.Result = Comparer.Default.Compare(e.Value1, e.Value2);
e.Handled = true;
}
And set the SortMode attribute for yout column as:
<Settings SortMode="Custom" />

Index out of range, error

my code sometimes throw error but sometimes not.
Error:
Index out of range.
code:
protected void btnGenerateReport_Click(object sender, EventArgs e)
{
GridViewSmsComplaints.DataBind();
dtRoom.Columns.Add(new DataColumn("ID", typeof(string)));
dtRoom.Columns.Add(new DataColumn("RecievingDate", typeof(string)));
dtRoom.Columns.Add(new DataColumn("FromMobileNo", typeof(string)));
dtRoom.Columns.Add(new DataColumn("Message", typeof(string)));
dtRoom.Columns.Add(new DataColumn("IsComplaint", typeof(short)));
for (int i = 0; i <= 5; i++)
{
int ID = Convert.ToInt32(GridViewSmsComplaints.Rows[i].Cells[0].Text);
ManageRecievedMessage mngRecMsg = new ManageRecievedMessage();
DropDownList IsValid = (DropDownList) GridViewSmsComplaints.Rows[i].FindControl("ddlValidity");
short IsComplaint;
if (IsValid.SelectedValue == "1")
{
IsComplaint= Convert.ToInt16(IsValid.SelectedValue.ToString());
mngRecMsg.UpdateSmsComplaintValidity(ID, 1);
DataRow datarw = null;
datarw = dtRoom.NewRow();
datarw[0] = GridViewSmsComplaints.Rows[i].Cells[0].Text;
datarw[1] = GridViewSmsComplaints.Rows[i].Cells[1].Text;
datarw[2] = GridViewSmsComplaints.Rows[i].Cells[2].Text;
datarw[3] = GridViewSmsComplaints.Rows[i].Cells[3].Text;
datarw[4] = IsComplaint; //Convert.ToInt16(GridViewSmsComplaints.Rows[i].Cells[4].Text);
dtRoom.Rows.Add(datarw);
}
else if(IsValid.SelectedValue != "1" )
{
IsComplaint= Convert.ToInt16(IsValid.SelectedValue.ToString());
mngRecMsg.UpdateSmsComplaintValidity(ID, IsComplaint);
}
}
GridViewSmsComplaints.DataBind();
ReportViewer1.ProcessingMode = ProcessingMode.Local;
ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/Report_SmsComplaintsByDate.rdlc");
if (dtRoom.Rows.Count <= 0)
{
HiddenFieldSetMessage.Value = "NotExists";
HiddenFieldShowMessage.Value = "True";
ReportViewer1.Visible = false;
GridViewSmsComplaints.DataBind();
GridViewSmsComplaints.Visible = false;
}
else
{
ReportDataSource rpds = new ReportDataSource("DataSet1", dtRoom);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(rpds);
ReportViewer1.Visible = true;
GridViewSmsComplaints.DataBind();
GridViewSmsComplaints.Visible = false;
}
}
at this line:
int ID = Convert.ToInt32(GridViewSmsComplaints.Rows[i].Cells[0].Text);
my gridview is displaying two rows, among whihc i have to validate whether VALID (1) or invalid (0) from dropdown but it throws error but sometimes it doesn't.
ERROR:
Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"}
Your grid doesn't always have at least 5 rows so trying to index into the Rows collection causes your out of bounds exception. Looks a little odd to me that you're currently exepcting exactly 5 rows but if you're getting this error it is not the case.
To avoid the error change your code to this:
for (int i = 0; i < GridViewSmsComplaints.Rows.Count; i++)
{
int ID = Convert.ToInt32(GridViewSmsComplaints.Rows[i].Cells[0].Text);
....

Can't retrieve data entered in first empty row of grid view

I have placed grid view in update panel with first row as empty and it is not bound with any data base. Rather I have bound grid view with data table. Whenever I click on 'Add New Row' button, a new row is created in grid view there by retaining the data field in old rows but my problem is whenever I click on save button, at that time data of first row is not retried but I can get the data that is filled in second row and onwards. I have saved my data table in session and again retrieving it after each post back.
Here is the code of my .aspx.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using AppResumeMaster;
using System.Collections;
using AppQualificationDetail;
public partial class Applicant_ApplicationForm : System.Web.UI.Page
{
int Rows = 1;
object MaxAppId = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
setInitialRow();
}
}
protected void saveBtn_Click(object sender, EventArgs e)
{
try
{
using (DataOperation oDo = new DataOperation())
{
MaxAppId= oDo.ExecuteScaler("select max(AppId) from tblAppResumeMaster");
if (MaxAppId == System.DBNull.Value)
MaxAppId = 0;
}
using (AppResumeMasterClass objAppResumeMasterClass = new AppResumeMasterClass())
{
objAppResumeMasterClass.AppId = Convert.ToInt32(MaxAppId)+1;
objAppResumeMasterClass.AppFirstName = firstnameBox.Text;
objAppResumeMasterClass.AppLastName = lastnameBox.Text;
objAppResumeMasterClass.AppAddress1 = CurAddBox.Text;
objAppResumeMasterClass.AppCity1 = CurAddBox.Text;
objAppResumeMasterClass.AppState1 = CurStateBox.Text;
objAppResumeMasterClass.AppCountry1 = CurCountrybox.Text;
objAppResumeMasterClass.AppAddress2 = PerAddBox.Text;
objAppResumeMasterClass.AppCity2 = PerCityBox.Text;
objAppResumeMasterClass.AppState2 = PerStateBox.Text;
objAppResumeMasterClass.AppCountry2 = PerCountrybox.Text;
objAppResumeMasterClass.AppEmail1 = emailBox.Text;
objAppResumeMasterClass.AppEmail2 = AltEmailBox.Text;
objAppResumeMasterClass.AppMobileNo = mobileNoBox.Text;
objAppResumeMasterClass.AppContactNo = phoneNoBox.Text;
objAppResumeMasterClass.AppDOB = Convert.ToDateTime(birthDateBox.Text);
objAppResumeMasterClass.AppKeySkill = skillsBox.Text;
objAppResumeMasterClass.AppGoal = goalBox.Text;
objAppResumeMasterClass.AppWeakness = weaknessBox.Text;
objAppResumeMasterClass.AppStrengths = strengthsBox.Text;
objAppResumeMasterClass.setVal(1);
}
DataTable Table = (DataTable)Session["CurTable"];
int cnt = Table.Rows.Count;
using(AppQualificationDetailClass objAppQualificationDetail = new AppQualificationDetailClass())
{
for (int RowCnt = 0; RowCnt < Table.Rows.Count; RowCnt++)
{
objAppQualificationDetail.AppId = Convert.ToInt32(MaxAppId) + 1;
objAppQualificationDetail.QualiId = Convert.ToInt32(Table.Rows[RowCnt][1]);
objAppQualificationDetail.Year = Convert.ToInt32(Table.Rows[RowCnt][3]);
objAppQualificationDetail.Percentage = (float)Table.Rows[RowCnt][2];
objAppQualificationDetail.InstiName = Table.Rows[RowCnt][4].ToString();
objAppQualificationDetail.setVal(1);
}
}
ExistMsgLbl.Text = Table.Rows[0][2].ToString();
}
catch (Exception ex)
{
throw ex;
}
}
protected void addRowBtn_Click(object sender, EventArgs e)
{
AddNewRow();
}
protected void InstituteLbl_PreRender(object sender, EventArgs e)
{
//Session.Add("Table", Table1);
}
public void setInitialRow()
{
DataTable Table = new DataTable();
DataRow dr = null;
Table.Columns.Add(new DataColumn("Qualification",typeof(string)));
Table.Columns.Add(new DataColumn("QualiId",typeof(string)));
Table.Columns.Add(new DataColumn("Percentage",typeof(string)));
Table.Columns.Add(new DataColumn("Passing Year",typeof(string)));
Table.Columns.Add(new DataColumn("Institute Name",typeof(string)));
dr = Table.NewRow();
dr["Percentage"] = string.Empty;
dr["Passing Year"] = string.Empty;
dr["Institute Name"]=string.Empty;
Table.Rows.Add(dr);
Session.Add("CurTable", Table);
GridView1.DataSource = Table;
GridView1.DataBind();
ArrayList Array = new ArrayList();
DataSet ds = new DataSet();
DropDownList DDL = (DropDownList)GridView1.Rows[0].Cells[0].FindControl("QualificationList");
FillDropDownList(DDL);
}
public void AddNewRow()
{
DataSet ds=new DataSet();
int RowIndex = 0;
if (Session["CurTable"] != null)
{
DataTable CurTable = (DataTable)Session["CurTable"];
DataRow CurRow = null;
if (CurTable.Rows.Count > 0)
{
CurRow = CurTable.NewRow();
CurTable.Rows.Add(CurRow);
Session.Add("CurTable", CurTable);
for (int count = 0; count < CurTable.Rows.Count - 1; count++)
{
DropDownList DDL = (DropDownList)GridView1.Rows[count].Cells[0].FindControl("QualificationList");
TextBox PercentageBox = (TextBox)GridView1.Rows[count].Cells[1].FindControl("percentageBox");
TextBox yearBox = (TextBox)GridView1.Rows[count].Cells[1].FindControl("yearBox");
TextBox InstituteNameBox = (TextBox)GridView1.Rows[count].Cells[1].FindControl("InstituteNameBox");
CurTable.Rows[count]["Percentage"] = PercentageBox.Text;
CurTable.Rows[count]["Passing Year"]=yearBox.Text;
CurTable.Rows[count]["Institute Name"]=InstituteNameBox.Text;
CurTable.Rows[count]["Qualification"]=DDL.SelectedItem.Text;
CurTable.Rows[count]["QualiId"] = DDL.SelectedValue;
}
GridView1.DataSource = CurTable;
GridView1.DataBind();
}
}
setPreviousData();
}
public void setPreviousData()
{
int RowIndex = 0;
if (Session["CurTable"] != null)
{
DataTable RestoreTable = (DataTable)Session["CurTable"];
if (RestoreTable.Rows.Count > 0)
{
for (int row = 0; row < RestoreTable.Rows.Count; row++)
{
DropDownList DPList = (DropDownList)GridView1.Rows[row].Cells[0].FindControl("QualificationList");
TextBox PercentageBox = (TextBox)GridView1.Rows[row].Cells[1].FindControl("percentageBox");
TextBox YearBox = (TextBox)GridView1.Rows[row].Cells[2].FindControl("yearBox");
TextBox InstituteName = (TextBox)GridView1.Rows[row].Cells[3].FindControl("InstituteNamebox");
FillDropDownList(DPList);
if (row < RestoreTable.Rows.Count - 1)
{
PercentageBox.Text = RestoreTable.Rows[row]["Percentage"].ToString();
YearBox.Text = RestoreTable.Rows[row]["Passing Year"].ToString();
InstituteName.Text = RestoreTable.Rows[row]["Institute Name"].ToString();
DPList.ClearSelection();
DPList.Items.FindByText(RestoreTable.Rows[row]["Qualification"].ToString()).Selected = true;
}
RowIndex++;
}
}
}
}
private ArrayList FillArrayList()
{
ArrayList ArrayList = new ArrayList();
DataSet ds = new DataSet();
using(DataOperation oDo = new DataOperation())
{
ds =oDo.DropDownList("select * from tblQualificationMaster");
for(int count=0;count<ds.Tables[0].Rows.Count;count++)
{
ArrayList.Add(new ListItem(ds.Tables[0].Rows[count][1].ToString(), ds.Tables[0].Rows[count][0].ToString()));
}
}
return ArrayList;
}
private void FillDropDownList(DropDownList DDL)
{
ArrayList ArrayList = FillArrayList();
foreach (ListItem item in ArrayList)
{
DDL.Items.Add(item);
}
}
}
Use ViewState instead of Session.

Resources