Can't retrieve data entered in first empty row of grid view - asp.net

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.

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!

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

Retain textbox values while Gridview Paging

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.

Editable gridview based on list

Is it possible to create a gridview based on a list? I have the following list:
ID = 1
Name = John
Zip = 33141
ID = 2
Name = Tim
Zip = 33139
I want to be able to create an editable gridview with this list
When i bind it to the grid view, it seems to put everyting in one column, and i can't figure out how to get it to seperate it into different columns
Here is my code for setting the DataSource of the GridView:
DataTable table = ConvertListToDataTable(personList);
GridView1.DataSource = table;
GridView1.DataBind();
static DataTable ConvertListToDataTable(List<string> list)
{
// New table.
DataTable table = new DataTable();
// Get max columns.
int columns = 7;
// Add columns.
for (int i = 0; i < columns; i++)
{
table.Columns.Add();
}
// Add rows.
foreach (var rd in list)
{
table.Rows.Add(rd);
}
return table;
}
Here is an example:
private class Person
{
int m_iID;
string m_sName;
string m_sZip;
public int ID { get { return m_iID; } }
public string Name { get { return m_sName; } }
public string Zip { get { return m_sZip; } }
public Person(int iID, string sName, string sZip)
{
m_iID = iID;
m_sName = sName;
m_sZip = sZip;
}
}
private List<Person> m_People;
private void ConvertListToDataTable(List<Person> People)
{
DataTable table = new DataTable();
DataColumn col1 = new DataColumn("ID");
DataColumn col2 = new DataColumn("Name");
DataColumn col3 = new DataColumn("Zip");
col1.DataType = System.Type.GetType("System.String");
col2.DataType = System.Type.GetType("System.String");
col3.DataType = System.Type.GetType("System.String");
table.Columns.Add(col1);
table.Columns.Add(col2);
table.Columns.Add(col3);
foreach (Person person in People)
{
DataRow row = table.NewRow();
row[col1] = person.ID;
row[col2] = person.Name;
row[col3] = person.Zip;
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
}

how to find which imagebutton was clicked?

I have created a function which displays a bus seat layout, dynamically. Now after adding all this dynamically created table and cells into a tag, I want to know which imagebutton was clicked.I have also mentioned proper ID to each imagebutton in cell.
public void DisplaySeatLayout(ListBus _listBus) {
//fetching data from database
SeatBUS _seatBUS = new SeatBUS();
DataTable dt = _seatBUS.GetAllSeatByBusRouter(_listBus);
//Layout generation code
ImageButton img ;
HtmlTable table = new HtmlTable();
table.Attributes.Add("runat", "server");
table.Attributes.Add("id", "LayoutTable");
HtmlTableRow [] tr = new HtmlTableRow[] { new HtmlTableRow(), new HtmlTableRow(), new HtmlTableRow(),new HtmlTableRow(),new HtmlTableRow()};
HtmlTableCell tc = null;
int SeatNo=0;
//Getting Total no of seats.
int MaxSeatNo = dt.Rows.Count;
//Iterating datatable
//Displaying labels for displaying column names in the table
for (int columnCounter = 0; columnCounter < 8; columnCounter++){
for (int rowCounter = 0; rowCounter < 5; rowCounter++){
if (SeatNo < MaxSeatNo){
if (rowCounter == 2 && columnCounter < 7){
tc = new HtmlTableCell();
Label lbl = new Label();
lbl.Text = "";
lbl.ID = "lbl " + rowCounter.ToString() + columnCounter.ToString();
tc.Controls.Add(lbl);
tr[rowCounter].Controls.Add(tc);
//reducing seat number for sake of sequence.
}
else{
//adding label in each cell.
tc = new HtmlTableCell();
Label lbl = new Label();
lbl.Text = dt.Rows[SeatNo]["NumberSeat"].ToString();
lbl.ID = "lbl " + rowCounter.ToString() + columnCounter.ToString();
tc.Controls.Add(lbl);
//adding imagebutton in each cell .
img = new ImageButton();
img.Attributes.Add("type", "image");
img.Attributes.Add("id", rowCounter.ToString());
img.CssClass = "seatRightMostRow1";
img.ImageUrl = "../Images/available_seat_img.png";
img.ID = dt.Rows[SeatNo]["NumberSeat"].ToString();
img.Click += new ImageClickEventHandler(Imagebutton_Click);
tc.Controls.Add(img);
tr[rowCounter].Controls.Add(tc);
SeatNo++;
}
}//SeatNo < MaxSeatNo
table.Controls.Add(tr[rowCounter]);
}
seatArranngement.Controls.Add(table);
}
}
this is complete code after suggestion.
function that is displaying dynamic table is inside Page_load
protected void Page_Load(object sender, EventArgs e)
{
_listBusBUS = new ListBusBUS();
_routerBUS = new RouterBUS();
_listBus = new ListBus();
_promoteBUS = new PromoteBUS();
if (!Page.IsPostBack)
{
LoadData();
}
DisplaySeatLayout();
}
Also here i have copied code in prerender
protected override void OnPreRender(EventArgs e)
{
if (MultiView1.ActiveViewIndex == 1)
{
int listBusID = int.Parse(hdlListBusID.Value.ToString());
_listBus = _listBusBUS.GetAllListBusById(listBusID);
litListBusID.Text = _listBus.ListBusID.ToString();
litRouterID.Text = _listBus.RouterID.ToString();
litArrival.Text = _listBus.Arrival.ToString();
litDeparture.Text = _listBus.Departure.ToString();
litPrice.Text = _listBus.Price.ToString();
}
else if (MultiView1.ActiveViewIndex == 2)
{
//original code starts from here
litListBusIDS.Text = litListBusIDS.Text;
litRouterIDS.Text = litRouterID.Text;
litArrivalS.Text = litArrival.Text;
litDepartureS.Text = litDeparture.Text;
litSeat.Text = hdlSeat.Value;// chkSeat.SelectedItem.Text;
litPrices.Text = litPrice.Text;
//hdlSeat.Value = chkSeat.SelectedItem.Text.ToString();
}
else if (MultiView1.ActiveViewIndex == 3)
{
litCustomerNameStep4.Text = txtcustomername.Text;
litSeatStep4.Text = litSeat.Text;
litPriceStep4.Text = litPrices.Text;
}
base.PreRender(e);
}
Also, layout is getting created twice if i click on any imagebutton.
All you have to do is get the value that you already placed inside the "id" attribute.
You can do this inside the Imagebutton_Click even you created:
protected void Imagebutton_Click(object sender, EventArgs e)
{
ImageButton b = sender as ImageButton;
string id = b.Attributes["id"]; // Returns the id
}

Resources