How to find duplicates value on gridview - asp.net

I have a gridview data and want to highlight the duplicates values. I want to change all the duplicates value color become red.
gridview data:
ID | Items |
1 | Item1 | --> this will be red
2 | Item2 |
1 | Item1 | --> this will be red
1 | Item1 | --> this will be red
Protected Sub GridView1_RowDataBound(ByVal sender As GridView, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim idxPrev As Integer = e.Row.RowIndex - 1
If 1 <= e.Row.RowIndex Then
If e.Row.Cells(3).Text = sender.Rows(idxPrev).Cells(3).Text Then
e.Row.ForeColor = Drawing.Color.Red
sender.Rows(idxPrev).ForeColor = Drawing.Color.Red
End If
End If
End If
End Sub
my code only able to change a certain data, because I set the idxPrev only for the previous one, so it only change able to detect the previous index. I want it to check and change all of the gridview duplicates data. is it possible to do that? would you mind to help me to solve this problem?
Thanks in advances....

Try this please.
SOURCE
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
<asp:BoundField DataField="Items" HeaderText="Items" ItemStyle-Width="150" />/>
</Columns>
</asp:GridView>
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
bind();
}
protected void bind()
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tblSample";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
HighlightDuplicate(this.GridView1);
con.Close();
}
public void HighlightDuplicate(GridView gridview)
{
for (int currentRow = 0; currentRow < gridview.Rows.Count - 1; currentRow++)
{
GridViewRow rowToCompare = gridview.Rows[currentRow];
for (int otherRow = currentRow + 1; otherRow < gridview.Rows.Count; otherRow++)
{
GridViewRow row = gridview.Rows[otherRow];
bool duplicateRow = true;
if (int.Parse(rowToCompare.Cells[0].Text) != int.Parse(row.Cells[0].Text))
{
duplicateRow = false;
}
else if (duplicateRow)
{
rowToCompare.BackColor = Color.Red;
row.BackColor = Color.Red;
}
}
}
}
Add the following namespaces too in the code behind page.
using System.Data;
using System.Drawing;

/*highlight duplicate row in gridview */
public void HighlightDuplicate(GridView GridView1)
{
for (int ThisRow = 0; ThisRow < GridView1.Rows.Count - 1; ThisRow++)
{
Label lbl_cd = (Label)GridView1.Rows[ThisRow].FindControl("lblcd");
lblhidcd.Value = lbl_EmpCode.Text;
GridViewRow CompareRow =`enter code here` GridView1.Rows[ThisRow];
for (int NextRow = ThisRow + 1; NextRow < GridView1.Rows.Count; NextRow++)
{
GridViewRow row = GridView1.Rows[NextRow];
bool DuplicateRow = true;
Label lbl_cd1= (Label)GridView1.Rows[NextRow].FindControl("lblcd");
hidnxtrowhidcd.Value = lbl_cd1= .Text;
if ((lblhidcd.Value) == (hidnxtrowhidcd.Value ))
{
row.BackColor = System.Drawing.Color.BlanchedAlmond;
CompareRow.BackColor = System.Drawing.Color.BlanchedAlmond;
}
else if (DuplicateRow)
{
DuplicateRow = false;
}
}
}
}

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!

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.

how to show pattern in asp-Repeater item template?

I have a page in my asp.net project where I want to show the attendance of the employees. When present P should be shown and when absent then A and on holidays H should be shown in the repeater. Now on my web page I have 2 textboxes through which I enter the year and the month and for that month I want to get the attendance. My database tables are as follows.
(1) Calender
CalederID Year Month WorkingDays
1 2013 January 1111001111100111110011111001111
2 2013 February 1001111100111110011111001111
and so on . Here 1 represent the working days in the month and 0's are Saturday's and Sunday's
am using this pattern because on one of my page am getting checkboxes checked for (sat and sun) and unchecked for others so I know that these are holidays
(2) Attendance Table
AttendanceID EmpID PresentDays CalenderID LeaveDate
1 1 Null 1 2013-01-14
2 1 Null 2 2013-02-15
3 1 Null 4 2013-04-11
4 3 Null 6 2013-06-26
(3) EmpInfo Table
EmpID EmpName and so on
1 Joe
2 Sandra
Now coming to the problem on my web page when I enter the year and month I want to show the repeater with headers as Date Numbers which represent the dates of that month. Now if the month has 30 days then 30 numbers are shown. Another repeater is used which has to show the attendance in the format P,A,H as told above
My Repeaters look like this
<table class="table1" >
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<tr>
<td>Employee ID</td>
</HeaderTemplate>
<ItemTemplate>
<td><asp:Label ID="lbldates" runat="server" Text='<%# Eval("Dates") %>' ></asp:Label></td>
</ItemTemplate>
<FooterTemplate>
<td>TOTAL</td></tr>
<tr>
</FooterTemplate>
</asp:Repeater>
<asp:Repeater id="rptAttendance" runat="server" OnItemDataBound="rptAttendance_ItemDataBound">
<ItemTemplate>
<tr>
<td><asp:Label ID="lblEmpName" runat="server" /></td>
<asp:Repeater ID="rptAttendanceCode" runat="server" OnItemDataBound="rptAttendanceCode_ItemDataBound" >
<ItemTemplate><td><asp:Label ID="lblAttendanceCode" runat="server" /></td></ItemTemplate>
</asp:Repeater>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
and the code behind is
protected void Page_Load(object sender, EventArgs e)
{
}
public void search(object sender, EventArgs e)
{
string cnnString = "Server=localhost;Port=3307;Database=leavesystem;Uid=root;Pwd=ashish";
MySqlConnection cnx = new MySqlConnection(cnnString);
cnx.Open();
string cmdText1 = "SELECT DAY(LAST_DAY(CAST(CONCAT('" + year.Value + "', '-', MONTH(STR_TO_DATE('" + month.Value + "', '%M')), '-', 1) AS DATE))) ";
MySqlCommand cmd1 = new MySqlCommand(cmdText1, cnx);
MySqlDataAdapter adapter1 = new MySqlDataAdapter();
DataSet ds1 = new DataSet();
adapter1.SelectCommand = cmd1;
adapter1.Fill(ds1);
DataRow dr;
dr = ds1.Tables[0].Rows[0];
string value = dr[0].ToString();
string cmdText2 = "SELECT Dates from temp where Dates <= " + value + " ";
MySqlCommand cmd2 = new MySqlCommand(cmdText2, cnx);
MySqlDataAdapter adapter2 = new MySqlDataAdapter();
DataSet ds2 = new DataSet();
adapter2.SelectCommand = cmd2;
adapter2.Fill(ds2);
DataTable dt = ds2.Tables[0];
Repeater1.DataSource = dt;
Repeater1.DataBind();
string cmdText3 = "SELECT CalenderID, WorkingDays from calender where Year = '" + year.Value + "' and Month = '" + month.Value + "' ";
MySqlCommand cmd3 = new MySqlCommand(cmdText3, cnx);
MySqlDataAdapter adapter3 = new MySqlDataAdapter();
DataSet ds3 = new DataSet();
adapter3.SelectCommand = cmd3;
adapter3.Fill(ds3);
DataTable calender = ds3.Tables[0];
DataRow dr3;
dr3 = ds3.Tables[0].Rows[0];
string CalenderID = dr3[0].ToString();
string cmdText4 = "SELECT EmpID,EmpName from empinfo ";
MySqlCommand cmd4 = new MySqlCommand(cmdText4, cnx);
MySqlDataAdapter adapter4 = new MySqlDataAdapter();
DataSet ds4 = new DataSet();
adapter4.SelectCommand = cmd4;
adapter4.Fill(ds4);
DataTable employees = ds4.Tables[0];
string cmdText5 = "SELECT EmpID,DAY(LeaveDate) AS LeaveDayOfMonth from attendance where CalenderID = '" + CalenderID + "' ";
MySqlCommand cmd5 = new MySqlCommand(cmdText5, cnx);
MySqlDataAdapter adapter5 = new MySqlDataAdapter();
DataSet ds5 = new DataSet();
adapter5.SelectCommand = cmd5;
adapter5.Fill(ds5);
DataTable attendance = ds5.Tables[0];
List<Tuple<string, string[]>> info = new List<Tuple<string, string[]>>();
int calendarID = calender.Rows[0].Field<int>("CalenderID");
string days = calender.Rows[0].Field<string>("WorkingDays");
days = days.Replace("1", "P");
days = days.Replace("0", "H");
string[] daysList = days.Select(d => d.ToString()).ToArray();
int present = 0;
int holidays = 0;
for (int i = 0; i < daysList.Length; ++i)
{
if (daysList[i] == "P")
present++;
if (daysList[i] == "H")
holidays++;
}
int working = (monthdays - holidays);
string total = (present + "/" + working);
Tuple<string, string[],string> employeeAttendance = null;
foreach (DataRow employee in employees.Rows)
{
employeeAttendance = new Tuple<string, string[],string>(employee.Field<string>("EmpName"), daysList,total);
foreach (DataRow absentDay in attendance.AsEnumerable().Where(a => a.Field<int>("EmpID") == employee.Field<int>("EmpID")))
{
var leaveDay = absentDay.Field<Int64>("LeaveDayOfMonth");
int leaveDay1 = Convert.ToInt16(leaveDay);
leaveDay1 = leaveDay1 - 1;
employeeAttendance.Item2[leaveDay1] = "A";
}
info.Add(employeeAttendance);
}
this.rptAttendance.DataSource = info;
this.rptAttendance.DataBind();
}
protected void rptAttendance_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Tuple<string, string[],string> info = (Tuple<string, string[],string>)e.Item.DataItem;
((Label)e.Item.FindControl("lblEmpName")).Text = info.Item1;
((Label)e.Item.FindControl("lbltotal")).Text = info.Item3;
Repeater attendanceCode = (Repeater)e.Item.FindControl("rptAttendanceCode");
attendanceCode.DataSource = info.Item2;
attendanceCode.DataBind();
}
}
protected void rptAttendanceCode_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
((Label)e.Item.FindControl("lblAttendanceCode")).Text = e.Item.DataItem.ToString();
}
}
In code behind I get the number of days in the month then compare it with a table which has 31 dates and from that logic I dsplay my numbers and on the bottom left using repeater 2 to show my EmpID's and now beside them below the date numbers I want to show the attendance. Can some one tell me how to do this. The PresendtDays columns in my attendance table is empty but I dont know how to use that. Please help me out I have been trying this from many hours and that is why I posted my complete code so that some one would help me. Looking for an early response. Thanks in advance !!
Due to the unconventional design of your database, I had to do some major data manipulation to make this work. That being said, here is my proposed solution.
Instead of the SQL statement "SELECT EmpID from empinfo ", you will need to perform three additional queries:
Retrieve info from the Calendar table:
SELECT CalendarID, WorkingDays FROM Calendar WHERE Year = [YEAR] and Month = [MONTH]
This will return a table that looks like this:
Retrieve info from the Calendar table using the CalendarID:
SELECT EmpID, EmpName FROM Employees
This will return a table that looks like this:
Retrieve info from Attendance table, using the CalendarID from the first query.
SELECT EmpID, DAY(LeaveDate) AS LeaveDayOfMonth FROM Attendance WHERE CalendarID = [CALENDAR ID]
This will return a table that looks like this:
Once you have done this, replace your second repeater (Repeater2) with the following TWO repeaters. The, first repeater (rptAttendance) lists each employee, the second repeater (rptAttendanceCode) list each day of the month for the employee. (Note, we are connecting to the repeaters's OnItemDataBound event, more on this later):
<asp:Repeater id="rptAttendance" runat="server" OnItemDataBound="rptAttendance_ItemDataBound">
<ItemTemplate>
<tr>
<td><asp:Label ID="lblEmpName" runat="server" /></td>
<asp:Repeater ID="rptAttendanceCode" runat="server" OnItemDataBound="rptAttendanceCode_ItemDataBound" >
<ItemTemplate><td><asp:Label ID="lblAttendanceCode" runat="server" /></td></ItemTemplate>
</asp:Repeater>
</tr>
</ItemTemplate>
</asp:Repeater>
Now, this is where the fun starts!
First, you need to create a data structure that hold the employee name and his/her attendance for each day of the month. We will use the WorkingDays field for our base line and append it with each employee's attendance (taken from the Attendance table).
//This list (info) holds the employee's name in the first string, and their attendance in the string array
List<Tuple<string, string[]>> info = new List<Tuple<string, string[]>>();
int calendarID = calendar.Rows[0].Field<int>("CalendarID");
string days = calendar.Rows[0].Field<string>("WorkingDays");
Replace the day-type code with the corresponding letter
days = days.Replace("1", "P");
days = days.Replace("0", "H");
Convert this into an an array so we can iterate over it
string[] daysList = days.Select(d => d.ToString()).ToArray();
Now we will iterate over each employee record and create a data structure for each employee. Then we will iterate over each employee's day off and update their daylist collection with the days that they were not at work.
foreach (DataRow employee in employees.Rows)
{
employeeAttendance = new Tuple<string, string[]>(employee.Field<string>("EmpName"), daysList);
foreach (DataRow absentDay in attendance.AsEnumerable().Where(a => a.Field<int>("EmpID") == employee.Field<int>("EmpID")))
{
employeeAttendance.Item2[absentDay.Field<int>("LeaveDayOfMonth") - 1] = "A";
}
info.Add(employeeAttendance);
}
Here are each repeater's ItemDataBound event handlers:
protected void rptAttendance_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Tuple<string, string[]> info = (Tuple<string, string[]>)e.Item.DataItem;
((Label)e.Item.FindControl("lblEmpName")).Text = info.Item1;
Repeater attendanceCode = (Repeater)e.Item.FindControl("rptAttendanceCode");
attendanceCode.DataSource = info.Item2;
attendanceCode.DataBind();
}
}
protected void rptAttendanceCode_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
((Label)e.Item.FindControl("lblAttendanceCode")).Text = e.Item.DataItem.ToString();
}
}
Here is the code-behind in its entirety:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Tuple<string, string[]>> info = new List<Tuple<string, string[]>>();
int calendarID = calendar.Rows[0].Field<int>("CalendarID");
string days = calendar.Rows[0].Field<string>("WorkingDays");
days = days.Replace("1", "P");
days = days.Replace("0", "H");
string[] daysList = days.Select(d => d.ToString()).ToArray();
Tuple<string, string[]> employeeAttendance = null;
foreach (DataRow employee in employees.Rows)
{
employeeAttendance = new Tuple<string, string[]>(employee.Field<string>("EmpName"), daysList);
foreach (DataRow absentDay in attendance.AsEnumerable().Where(a => a.Field<int>("EmpID") == employee.Field<int>("EmpID")))
{
employeeAttendance.Item2[absentDay.Field<int>("LeaveDayOfMonth") - 1] = "A";
}
info.Add(employeeAttendance);
}
this.rptAttendance.DataSource = info;
this.rptAttendance.DataBind();
}
}
protected void rptAttendance_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Tuple<string, string[]> info = (Tuple<string, string[]>)e.Item.DataItem;
((Label)e.Item.FindControl("lblEmpName")).Text = info.Item1;
Repeater attendanceCode = (Repeater)e.Item.FindControl("rptAttendanceCode");
attendanceCode.DataSource = info.Item2;
attendanceCode.DataBind();
}
}
protected void rptAttendanceCode_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
((Label)e.Item.FindControl("lblAttendanceCode")).Text = e.Item.DataItem.ToString();
}
}

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