Index out of range, error - asp.net

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

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

SQL MDF Database every cell displays: "System.__ComObject"

When I execute this program the Excel part generates and string array: cellValue just fine.
When it inserts into the SQL MDF Database: MDFExcel every cell displays: "System.__ComObject".
How do you display the string value instead of the "System.__ComObject"?
protected void Button1_Click(Object sender, EventArgs e)
{
DataSet ds = new DataSet();
//From Excel
Microsoft.Office.Interop.Excel.Application exlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook exlWb = exlApp.Workbooks.Open(#"C:\Users\Optiplex760\Documents\a Excel\ExcelToMDF.xls");
Microsoft.Office.Interop.Excel.Worksheet exlWs= exlWb.Sheets["Sheet1"];
Microsoft.Office.Interop.Excel.Range usedRange = exlWs.UsedRange;
int col = Convert.ToInt32(usedRange.Columns.Count);
int row = Convert.ToInt32(usedRange.Rows.Count);
exlApp.Visible = true;
string[,] cellValue = new string[row + 1, col + 1];
for (int j = 1; j <= row-1; j++)
{
for (int k = 1; k <= col-1; k++)
{
cellValue[j, k] = exlWs.Cells[j+1,k+1].ToString();
}
}
exlWb.Close();
exlWs = null;
exlWb = null;
exlApp.Quit();
exlApp = null;
//To MSSQL
String connStr, cmdStr;
connStr = ConfigurationManager.ConnectionStrings["MDFExceldb"].ConnectionString;
for (int h = 1; h<row; h++)
{
cmdStr = "INSERT INTO [Table1] (col1,col2,col3) VALUES (#col1,#col2,#col3);";
try
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#col1", cellValue[1, h]);
cmd.Parameters.AddWithValue("#col2", cellValue[2, h]);
cmd.Parameters.AddWithValue("#col3", cellValue[3, h]);
cmd.ExecuteNonQuery();
conn.Close();
cmd.Dispose();
conn.Dispose();
}
}
}
catch (Exception ex)
{
Label2.Text = ex.ToString();
}
}
}
Worksheet.Cells returns a Range and not a single value - and a Range (an RCW object) does not implemented a sensible ToString; thus it defaults to the "System.__ComObject" value shown.
Use the Text property of the Range, eg.
cellValue[j, k] = Convert.ToString(exlWs.Cells[j+1,k+1].Text);
While this should fix the immediate problem, it is also an inefficient process. See this response (using the Value/Value2 property) for how to access the Range values as a 2-dimensional array and reduce excessive range-slicing.

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
}

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