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();
}
}
Related
I have a news website , each news had an ID in my database table , I choose 4 IDs randomly to put their titles in the "see more" section .. I select the ID by generating a random row number , the problem is when I click on one of the suggested news it takes me to another news randomly ! which makes no sense to me . the weird thing is the other random ID that I'm taken to does exist but not the one that I clicked.
Latelty I noticed this : for example in the "see more" section we have title1 - title2 - title3 - title4 , so I clicked on title1 it takes me to another random news which i didn't click .. now the 4 titles in the "see more" section are different which is normal .. now when I click in title2 it will take me to the current news in title1 ! and so on next time when i click in title1 it will take me to the curent news in title2 . I can't understand the relation
I tried to store the random numbers in another variables (key1,key2..) before putting one of them in the session but It's still the same problem.
I tried also not refreshing the page (I mean depending just the post back).
I tried clearing the season also tried reomving them all before storing the news Id. There is no error messages.
int myrandom1;
int myrandom2;
int myrandom3;
int myrandom4;
string key1;
string key2;
string key3;
string key4;
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
string key=" ";
key = Session["key"].ToString();
SqlConnection con = new SqlConnection("Data Source=.; initial catalog=celeblogy; integrated security=true");
SqlCommand cmd = new SqlCommand("select * from news where id like '" + key + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "new");
string Titre = ds.Tables["new"].Rows[0][1].ToString();
Titre = Titre.Replace("*", "'");
titre.InnerText = Titre;
string blog = Decode(ds.Tables["new"].Rows[0][2].ToString());
string[] Blogs;
blog = blog.Replace("*", "'");
Blogs = blog.Split('#');
Literal1.Text = Blogs[0];
Image1.Attributes["src"] = "pictures/" + key + "1.jpg";
if (Blogs.Length >= 2)
{
Literal2.Text = Blogs[1];
Image2.Attributes["src"] = "pictures/" + key + "2.jpg";
}
cmd = new SqlCommand("select * from news", con);
da = new SqlDataAdapter(cmd);
da.Fill(ds, "news");
Random rnd = new Random();
myrandom1 =rnd.Next(ds.Tables["news"].Rows.Count-1);
Image3.ImageUrl = "pictures/" + ds.Tables["news"].Rows[myrandom1][0].ToString()+"1.jpg";
Label1.Text =ds.Tables["news"].Rows[myrandom1][1].ToString().Replace("*","'");
key1 = ds.Tables["news"].Rows[myrandom1][0].ToString();
myrandom2 = rnd.Next(ds.Tables["news"].Rows.Count - 1);
Image4.ImageUrl = "pictures/" + ds.Tables["news"].Rows[myrandom2][0].ToString() + "1.jpg";
Label2.Text = ds.Tables["news"].Rows[myrandom2][1].ToString().Replace("*", "'");
key2 = ds.Tables["news"].Rows[myrandom2][0].ToString();
myrandom3 = rnd.Next(ds.Tables["news"].Rows.Count - 1);
Image5.ImageUrl = "pictures/" + ds.Tables["news"].Rows[myrandom3][0].ToString() + "1.jpg";
Label3.Text = ds.Tables["news"].Rows[myrandom3][1].ToString().Replace("*", "'");
key3 = ds.Tables["news"].Rows[myrandom3][0].ToString();
myrandom4 = rnd.Next(ds.Tables["news"].Rows.Count - 1);
Image6.ImageUrl = "pictures/" + ds.Tables["news"].Rows[myrandom4][0].ToString() + "1.jpg";
Label4.Text = ds.Tables["news"].Rows[myrandom4][1].ToString().Replace("*", "'");
key4 = ds.Tables["news"].Rows[myrandom4][0].ToString();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
Session["key"] =key1;
Response.Redirect(Request.RawUrl);
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
Session["key"] = key2;
Response.Redirect(Request.RawUrl);
}
protected void LinkButton3_Click(object sender, EventArgs e)
{
Session["key"] = key3;
Response.Redirect(Request.RawUrl);
}
protected void LinkButton4_Click(object sender, EventArgs e)
{
Session["key"] = key4;
Response.Redirect(Request.RawUrl);
}
picture of the see more section
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!
my code throws error:
Input string not in correct format
code:
protected void btnGenerateReport_Click(object sender, EventArgs e)
{
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)));
// bool var = false;
for (int i = 0; i <= 5; i++)
{
//drw = dtRoom.NewRow();
DropDownList IsValid = (DropDownList) GridViewSmsComplaints.Rows[i].FindControl("ddlValidity");
if (IsValid.SelectedValue == "1")
{
int ID = Convert.ToInt32(GridViewSmsComplaints.Rows[i].Cells[0].Text);
ManageRecievedMessage mngRecMsg = new ManageRecievedMessage();
mngRecMsg.UpdateSmsComplaintValidity(ID, 1);
//var = true;
DataRow datarw = null;
//dtRoom = new DataTable();
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] = Convert.ToInt16(GridViewSmsComplaints.Rows[i].Cells[4].Text);
dtRoom.Rows.Add(datarw);
it throws error at this line:
datarw[4] = Convert.ToInt16(GridViewSmsComplaints.Rows[i].Cells[4].Text);
it should pass 1 to datarw 4 since i am selecting it from dropdown.
<asp:DropDownList ID="ddlValidity" runat="server">
<asp:ListItem Value="-1" Text="-Select-"></asp:ListItem>
<asp:ListItem Value="1" Text="Valid"></asp:ListItem>
<asp:ListItem Value="0" Text="Invalid"></asp:ListItem>
</asp:DropDownList>
Your problem is because your Value is 1 but Text corresponding to it is "Valid". You are passing Text, which is not a number and so you get an error. Therefore, you should change your code to use the Value from the dropdown instead, like so:
datarw[4] = Convert.ToInt16(IsValid.SelectedValue);
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;
}
}
}
}
In following code i am trying to show the latest record on the top of repeater. I also want to include paging in repeater.Paging is done successful in page but i am having trouble when i do sorting in repeater.So my question is this that how can i do sorting and paging in repeater?
My code:
private void Get_Data()
{
String File = Server.MapPath("~/Data/BlogContent.xml");
DataSet ds = new DataSet();
ds.ReadXml(File);
DataView dv = new DataView(ds.Tables[0]);
dv.Sort = "id DESC";
DataTable dt = dv.Table;
ViewState.Add("Mytable", dt);
}
private void Bind_Data(int take, int pageSize)
{
PagedDataSource page = new PagedDataSource();
page.AllowCustomPaging = true;
page.AllowPaging = true;
DataTable dtv = (DataTable)ViewState["Mytable"];
DataView dv = new DataView();
dv = dtv.DefaultView;
dv.Sort = "id ASC";
dv.RowFilter = "id>=" + pageSize + " AND " + "id<=" + take;
page.DataSource = dv;
page.PageSize = psize;
Repeater1.DataSource = page;
Repeater1.DataBind();
if (!IsPostBack)
{
int rowcount = dtv.Rows.Count;
CreatePagingControl(rowcount);
}
}
For paging Check this.Here is full example of paging.link
paging and sorting
** Read the article:
Custom paging in Repeater control in asp.net(C#, VB)**
http://www.webcodeexpert.com/2013/05/custom-paging-in-repeater-control-in.html