How to Access elements of a checked/selected row elements of gridview - c#

I am working in windows 8.2 and was working to insert a selected row to my data base and i have web form which have a grideview with checkboxes to select/deselect and an event to insert.
the code of the web form is as
<asp:Panel runat="server" ID="pnlStudData">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:checkbox runat="server" ID="chKCheckAll" onclick="javascript:SelectAllCheckboxes(this)"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkCheck" onclick="javascript:CheckedCheckboxes(this)"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Id">
<ItemTemplate>
<asp:Label ID="lblStudName" runat="server" Text='<%#Eval("Stud_Id")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Text='<%#Eval("FirstName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Middle Name">
<ItemTemplate>
<asp:Label ID="lblMiddleName" runat="server" Text='<%#Eval("MiddleName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%#Eval("LastName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cumpase">
<ItemTemplate>
<asp:Label ID="lblCumpase" runat="server" Text='<%#Eval("Cumpase")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="College">
<ItemTemplate>
<asp:Label ID="lblCollege" runat="server" Text='<%#Eval("College")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Department">
<ItemTemplate>
<asp:Label ID="lblDept" runat="server" Text='<%#Eval("Dept")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Block">
<ItemTemplate>
<asp:Label ID="lblBlock" runat="server" Text='<%#Eval("Block")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dorm Number">
<ItemTemplate>
<asp:Label ID="lblDormNo" runat="server" Text='<%#Eval("Dorm")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
<br />
<asp:Button ID="Save" runat="server" Text="Save" Width="169px" Height="46px" OnClick="Save_Click" />
<br />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
</asp:Panel>
and the java script to select/deselect a check-box as
<script language="javascript" type="text/javascript">
function SelectAllCheckboxes(chk)
{
var totalRows = $("#<%=GridView1.ClientID%> tr").length;
var selected = 0;
$('#<%=GridView1.ClientID%>').find("input:checkbox").each(function () {
if (this != chk) {
this.checked = chk.checked;
selected += 1;
}
});
}
function CheckedCheckboxes(chk)
{
if(chk.checked)
{
var totalRows = $('#<%=GridView1.ClientID %> :checkboxes').length;
var checked = $('#<%=GridView1.ClientID %> :checkbox:checked').length;
if(checked==(totalRows-1))
{
$('#<%=GridView1.ClientID %>').find("input:checkbox").each(function () {
this.checked = true;
});
}
else
{
$('#<%=GridView1.ClientID %>').find('input:checkbox:first').removeAttr('checked');
}
}
else {
$('#<%=GridView1.ClientID %>').find('input:checkbox:first').removeAttr('checked');
}
}
</script>
and the button save click event which sends this selected row cells to a database class insert method as
foreach(GridViewRow gd in GridView1.Rows)
{
if ((gd.Cells[0].FindControl("chkCheck") as CheckBox).Checked)
{
// gd.Cells[0].Visible = false;
string stId = gd.Cells[1].Text.ToString();
string fName = gd.Cells[2].Text.ToString();
string mName = gd.Cells[3].Text.ToString();
string lName = gd.Cells[4].Text.ToString();
string cumpas = gd.Cells[5].Text.ToString();
string college = gd.Cells[6].Text.ToString();
string dept = gd.Cells[7].Text.ToString();
int bl = Convert.ToInt32(gd.Cells[8].Text);
int dormNo = Convert.ToInt32(gd.Cells[9].Text);
DbCon db = new DbCon();
if (db.RegisterStud(stId, fName, mName, lName, cumpas, college, dept, bl, dormNo) == 1)
{
Label1.Text = "You Have Inserted";
}
else
{
Label1.Text = "Errror";
}
}
else { Label1.Text = "Please select a row"; }
}
but i can't find each cells value and not assigned to those string variables.

When using <asp:TemplateField>, the data is not inside Cell but is contained in the Control present inside the Cell.
row.Cells[].Text works only when using <asp:BoundField> for GridView Columns.
So, There are two steps to read the value when using <asp:TemplateField>:
Access the Control inside Cell
Access the Value from Control in step 1
I see you did the above steps to read the Checkbox value from first Column already. Follow the same for all other Columns.
if ((gd.Cells[0].FindControl("chkCheck") as CheckBox).Checked)
{
// Step 1: Access the Control inside Cell
Label lblName = (Label)gd.Cells[1].FindControl("lblStudName");
// Step 2: Access the Value from Control in step 1
string Name = lblName.Text;
// Combine Step 1 & Step 2: Access Values in one line
string Name = ((Label)gd.Cells[1].FindControl("lblStudName")).Text;
string firstName = ((Label)gd.Cells[2].FindControl("lblFirstName")).Text;
// ....same way for all Columns which use a <asp:TemplateField>
}

Related

Cell Text Always &nbsp:

I want to display the text of a specific cell in a textbox whenever I select a row from my gridview but whenever i do this "&nbsp" is the only text that I get even though the cell is not empty. Data on the gridview is bound from my database and I made a function where all the data from my database will be bound on my gridview. Below is the code that I'm using.
textbox1.Text = myGridView.SelectedRow.Cells[3].Text;
Markup
<asp:GridView ID="TraineeGrid" runat="server" AutoGenerateSelectButton ="true" AllowSorting="True" ShowHeader="true"
ShowFooter="false" AutoGenerateColumns="False" AutoGenerateEditButton="false" ScrollBars="Auto"
OnRowEditing="TraineeGrid_RowEditing"
OnRowUpdating="TraineeGrid_RowUpdating" OnRowCancelingEdit="TraineeGrid_RowCancelingEdit"
DataKeyNames="ID" Width="100%"
CellPadding="4" ForeColor="#333333" GridLines="None" HorizontalAlign="Center"
EditRowStyle-VerticalAlign="Middle" OnInit="Page_Load" OnRowDataBound="TraineeGrid_RowDataBound" OnSelectedIndexChanging="TraineeGrid_SelectedIndexChanging" OnSelectedIndexChanged="TraineeGrid_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("Delegate") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rank/Position">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbRankPos" runat="server" Text="Rank/Position" CommandName="Sort"
CommandArgument="RankPos" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newRankPos" TabIndex="2" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("RankPos") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtRankPos" runat="server"
Text='<%# Eval("RankPos") %>'/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
Function that binds Data
private void PopulateData()
{
DataTable dataTable = new DataTable();
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["TestCS"].ConnectionString))
{
string path = "PopulateSQL.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
string sql = sb.ToString();
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
using (SqlDataAdapter dataAdapt = new SqlDataAdapter(cmd))
{
dataAdapt.Fill(dataTable);
ViewState["NormalGrid"] = dataTable;
}
}
}
}
if (dataTable.Rows.Count > 0)
{
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
}
else
{
//Displays 'No Data Found' to gridview if there are no data in table
dataTable.Rows.Add(dataTable.NewRow());
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
TraineeGrid.Rows[0].Cells.Clear();
TraineeGrid.Rows[0].Cells.Add(new TableCell());
TraineeGrid.Rows[0].Cells[0].ColumnSpan = dataTable.Columns.Count;
TraineeGrid.Rows[0].Cells[0].Text = "No Data Found";
TraineeGrid.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}
You can use this: textbox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
In OnSelectedIndexChanged :
protected void OnSelectedIndexChanged1(object sender, EventArgs e)
{
//Get the selected row
GridViewRow row = GridView1.SelectedRow;
if (row != null)
{
// With
// TextBox1.Text = (row.FindControl("lblLocalTime") as Label).Text;
// Without
TextBox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
}
}
Complete Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnSelectedIndexChanged="OnSelectedIndexChanged1" AutoGenerateSelectButton="true">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="150" />
</Columns>
I've already found a solution. The problem is Im using TemplateField instead of BoundField that's why I cant use .Cells[] to get the specific cell that I wanted to get. However, if you are using TemplateField you can use .FindControl() and put in the ID of the label where your binding of data happens (ex. Text ='<%# Eval("FirstName") %>'). You can see that I put label on ItemTemplate to call it's ID.
Markup
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbName" runat="server" Text = '<%# Eval("Delegate") %>'> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>' />
</EditItemTemplate>
</asp:TemplateField>
Code Behind
Label varName = (Label)rows.FindControl("lbName");
string name = varName.Text;

finding label in itemTemplate and bind data from code behind

I wanted to display value in a label (label inside itemTemplate)
i have tried this approach
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
if (string.IsNullOrEmpty(s) == false)
{
foreach (GridViewRow row in GridView1.Rows)
{
string LabelText = ((Label)row.FindControl("labelSelf")).Text;
LabelText = s;
Response.Write(LabelText+"test");
}
}
but nothing is shown in the label inside the gridview. IT should display the value of s.
Next approach was
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
Label labelSelfCollect = GridView1.FindControl("labelSelf") as Label;
labelSelfCollect.Text = "Self Collect at "+ s;
I got this error
System.NullReferenceException: Object reference not set to an instance of an object.
and the last approach that i have used is
string s = null;
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
s = address.getSelfCollectAddress(orderNoTracking);
if (string.IsNullOrEmpty(s) == false)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label labelcollect = row.FindControl("labelSelf") as Label;
labelcollect.Text = "self collect at "+ s;
}
}
}
using this method also it shows nothing.How should i assign the s value into this labelSelf(label inside itemTemplate)?
my aspx code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="772px" style="margin-left: 120px; text-align: left" Height="100px" DataKeyNames ="progressID" OnRowDataBound="GridView1_OnRowDataBound" OnRowDeleting="GridView1_RowDeleting" CellPadding="4" CssClass="rounded_corners" HeaderStyle-Height="40px">
<AlternatingRowStyle CssClass="rounded_corners tr tr" />
<Columns>
<asp:BoundField ControlStyle-BorderWidth="60" DataField="dateupdate" HeaderText="Date Update" DataFormatString="{0:dd/MM/yyyy}" >
<ControlStyle BorderWidth="60px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Progress">
<ItemTemplate >
<%# Eval("message") %>
<br />
<asp:label ID="labelRemark" runat="server" style="Font-Size:11.5px;" text='<%# Eval("remark") %>'></asp:label><br />
<asp:Label ID="labelSelf" runat="server" style="Font-Size:11.5px;" ></asp:Label><br />
<div id="div<%# Eval("progressID") %>" >
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
DataKeyNames="progressID" style="text-align:center; font-size:small;" CellPadding="4" OnRowCommand="GridView2_RowCommand" GridLines="None" CssClass="rounded_corners" Width="500px" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="tackingNo" HeaderText="Courier Tracking No" ItemStyle-Font-Size="Small" ItemStyle-Width="150px" >
</asp:BoundField>
<asp:BoundField DataField="courierDate" HeaderText="Courier Date">
</asp:BoundField>
<asp:TemplateField HeaderText="Provider">
<ItemTemplate>
<asp:HyperLink Text='<%#Eval("providernm")%>' Target="_blank" runat="server" DataNavigateUrlFields="companyurl" NavigateUrl='<%#Eval("companyurl")%>' ></asp:HyperLink>
<br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tracking" >
<ItemTemplate>
<br />
<asp:HyperLink Text="Track Here" Target="_blank" runat="server" DataNavigateUrlFields="trackingurl" NavigateUrl='<%#Eval("trackingurl")%>' ></asp:HyperLink>
<br />
<asp:Label ID="Label4" runat="server" Text="* check after 24 hours" Font-Italic="true"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="LinkButtonDELETE" runat="server" CommandName="Delete" Text="Delete" OnClientClick= "return confirm('Confirm Delete progress?')"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Thank you.
Use GridView1_OnRowDataBound instead of foreach (GridViewRow row in GridView1.Rows). Apart from that your first approach is correct. You're simply not assigning the Text property there but reading from it.
SelfCollectNameSpace.SelfCollect address = new SelfCollectNameSpace.SelfCollect();
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
Label labelSelf = (Label)e.Row.FindControl("labelSelf");
labelSelf.Text = address.getSelfCollectAddress(orderNoTracking); // maybe you need to retrieve the orderNoTracking from another control in this row or from it's datasource
}
}

How to display Gridview according to values in Database

I want to check for the services in TypeOfServices according to the ClientId, and check for all the services.
The database Columns are TaxId, ClientId, ClientName,TypeOfservice
The gridview should display Client names in alphabetical order,and the services present should display 'yes' else 'no'
I used this C# code but it's not working...
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblclientname = (Label)e.Row.FindControl("lblclientname");
Label lblincometax = (Label)e.Row.FindControl("lblincometax");
Label lblprofessionaltax = (Label)e.Row.FindControl("lblprofessionaltax");
Label lblservicetax = (Label)e.Row.FindControl("lblservicetax");
Label lbltds = (Label)e.Row.FindControl("lbltds");
Label lblvat = (Label)e.Row.FindControl("lblvat");
Label lblcompanylaw = (Label)e.Row.FindControl("lblcompanylaw");
string m = "SELECT * FROM tblTaxMaster";
ds = gs.getdata(m);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows.Count > 0)
{
string ClientId = ds.Tables[0].Rows[0]["ClientId"].ToString();
string TaxId = ds.Tables[0].Rows[0]["TaxId"].ToString();
string ser = "select TypeOfService from tblTaxMaster where ClientId= '" + ClientId.ToString() + "' and TaxId = '" + TaxId.ToString() + "' ";
ds = gs.getdata(ser);
if (ser == "INCOME TAX")
{
lblincometax.Text = "YES";
}
else
{
lblincometax.Text = "NO";
}
if (ser == "TDS")
{
lbltds.Text = "YES";
}
else
{
lbltds.Text = "NO";
}
if (ser == "PROFESSIONAL TAX")
{
lblprofessionaltax.Text = "YES";
}
else
{
lblprofessionaltax.Text = "NO";
}
if (ser == "SERVICE TAX")
{
lblservicetax.Text = "YES";
}
else
{
lblservicetax.Text = "NO";
}
if (ser == "VAT")
{
lblvat.Text = "YES";
}
else
{
lblvat.Text = "NO";
}
if (ser == "COMPANY LAW")
{
lblcompanylaw.Text = "YES";
}
else
{
lblcompanylaw.Text = "NO";
}
}
}
}
}
This is the ASP.Net Code
<asp:GridView ID="GridView1" runat="server" Width="550px"
AutoGenerateColumns="False" Font-Names="Cambria" Font-Size="10pt"
ShowFooter="True" FooterStyle-BackColor="#FF5600"
CellPadding="4" CssClass="grid-view" PageSize="20"
GridLines="None" ForeColor="#333333" onrowdatabound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField ItemStyle-Width="30px" HeaderText="Client Name">
<ItemTemplate>
<asp:Label ID="lblclientname" runat="server" Text='<%#Eval("ClientName")%>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="30px" HeaderText="Income Tax">
<ItemTemplate>
<asp:Label ID="lblincometax" runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="30px" HeaderText="Professional Tax">
<ItemTemplate>
<asp:Label ID="lblprofessionaltax" runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="30px" HeaderText="Service Tax">
<ItemTemplate>
<asp:Label ID="lblservicetax" runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="30px" HeaderText="TDS">
<ItemTemplate>
<asp:Label ID="lbltds" runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="30px" HeaderText="VAT">
<ItemTemplate>
<asp:Label ID="lblvat" runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="30px" HeaderText="Company Law">
<ItemTemplate>
<asp:Label ID="lblcompanylaw" runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="30px" HeaderText="">
<ItemTemplate>
<asp:Button ID="btnservicedetails" runat="server" Text="Service Details" />
</ItemTemplate>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#333333" />
<FooterStyle BackColor="#191919" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#191919" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E6E6E6" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
Why are looping if you are already getting the required values from
SELECT * FROM tblTaxMaster
When bind the gridview use joins and get the TypeOfService value in the select statement only and then modify your source code to
<asp:TemplateField ItemStyle-Width="30px" HeaderText="Client Name">
<ItemTemplate>
<asp:Label ID="lblclientname" runat="server" Text='<%#Eval("ClientName")%>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="30px" HeaderText="Income Tax">
<ItemTemplate>
<asp:Label ID="lblincometax" runat="server" Text='<%#Eval("typeOfService")%>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

In my Asp.net App, i have a GridView and i generate the data of column[6] by myself using code behind.
by looking at the code below, i have a footer for my gridview. and the problem is my text for column[6] won't appear if i use footer.
If i delete the footertext code, then my text for column[6] is appear. what is the problem? both of the code cant use togather? i already set ShowFooter="True"
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < (this.GridView1.Rows.Count); i++)
{
this.GridView1.Rows[i].Cells[6].Text = "testing";
//GridView1.Columns[1].FooterText ="footer 1";
}
}
.aspx
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="4"
ForeColor="#333333" GridLines="None" ShowFooter="True"
onrowdatabound="GridView1_RowDataBound">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:BoundField DataField="reportDate" HeaderText="Report Date" dataformatstring="{0:dd MMMM yyyy}" SortExpression="reportDate" />
<asp:BoundField DataField="sponsorBonus" HeaderText="Sponsor Bonus" dataformatstring="{0:0.00}" SortExpression="sponsorBonus" HtmlEncode="False" />
<asp:BoundField DataField="pairingBonus" HeaderText="Pairing Bonus" HtmlEncode="False" SortExpression="pairingBonus" dataformatstring="{0:c}" />
<asp:BoundField DataField="staticBonus" HeaderText="Static Bonus" SortExpression="staticBonus" />
<asp:BoundField DataField="leftBonus" HeaderText="Left Bonus" SortExpression="leftBonus" />
<asp:BoundField DataField="rightBonus" HeaderText="Right Bonus" SortExpression="rightBonus" />
<asp:BoundField HeaderText="Total" SortExpression="total" >
<ItemStyle Width="100px" />
</asp:BoundField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
Sample Code: To set Footer text programatically
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = grdTotal.ToString("c");
}
}
UPDATED CODE:
decimal sumFooterValue = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string sponsorBonus = ((Label)e.Row.FindControl("Label2")).Text;
string pairingBonus = ((Label)e.Row.FindControl("Label3")).Text;
string staticBonus = ((Label)e.Row.FindControl("Label4")).Text;
string leftBonus = ((Label)e.Row.FindControl("Label5")).Text;
string rightBonus = ((Label)e.Row.FindControl("Label6")).Text;
decimal totalvalue = Convert.ToDecimal(sponsorBonus) + Convert.ToDecimal(pairingBonus) + Convert.ToDecimal(staticBonus) + Convert.ToDecimal(leftBonus) + Convert.ToDecimal(rightBonus);
e.Row.Cells[6].Text = totalvalue.ToString();
sumFooterValue += totalvalue;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = sumFooterValue.ToString();
}
}
In .aspx Page
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="4"
ForeColor="#333333" GridLines="None" ShowFooter="True"
onrowdatabound="GridView1_RowDataBound">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:TemplateField HeaderText="Report Date" SortExpression="reportDate">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("reportDate") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("reportDate", "{0:dd MMMM yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sponsor Bonus" SortExpression="sponsorBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("sponsorBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Bind("sponsorBonus", "{0:0.00}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Pairing Bonus" SortExpression="pairingBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("pairingBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"
Text='<%# Bind("pairingBonus", "{0:c}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Static Bonus" SortExpression="staticBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Left Bonus" SortExpression="leftBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Right Bonus" SortExpression="rightBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" SortExpression="total">
<EditItemTemplate>
<asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltotal" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
protected void gvBill_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
Total += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "InvMstAmount"));
else if (e.Row.RowType == DataControlRowType.Footer)
e.Row.Cells[7].Text = String.Format("{0:0}", "<b>" + Total + "</b>");
}
This can be achieved through LINQ with grouping, here a list of items pointed as a data source to the actual grid view.
Sample pseudo code which could help coding the actual.
var tabelDetails =(from li in dc.My_table
join m in dc.Table_One on li.ID equals m.ID
join c in dc.Table_two on li.OtherID equals c.ID
where //Condition
group new { m, li, c } by new
{
m.ID,
m.Name
} into g
select new
{
g.Key.ID,
Name = g.Key.FullName,
sponsorBonus= g.Where(s => s.c.Name == "sponsorBonus").Count(),
pairingBonus = g.Where(s => s.c.Name == "pairingBonus").Count(),
staticBonus = g.Where(s => s.c.Name == "staticBonus").Count(),
leftBonus = g.Where(s => s.c.Name == "leftBonus").Count(),
rightBonus = g.Where(s => s.c.Name == "rightBonus").Count(),
Total = g.Count() //Row wise Total
}).OrderBy(t => t.Name).ToList();
tabelDetails.Insert(tabelDetails.Count(), new //This data will be the last row of the grid
{
Name = "Total", //Column wise total
sponsorBonus = tabelDetails.Sum(s => s.sponsorBonus),
pairingBonus = tabelDetails.Sum(s => s.pairingBonus),
staticBonus = tabelDetails.Sum(s => s.staticBonus),
leftBonus = tabelDetails.Sum(s => s.leftBonus),
rightBonus = tabelDetails.Sum(s => s.rightBonus ),
Total = tabelDetails.Sum(s => s.Total)
});
<asp:TemplateField HeaderText="ExEmp" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
FooterStyle-BackColor="BurlyWood" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:TextBox ID="txtNoOfExEmp" runat="server" CssClass="form-control input-sm m-bot15"
Font-Bold="true" onkeypress="return isNumberKey(event)" Text='<%#Bind("ExEmp") %>'></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" Width="50px" />
<FooterTemplate>
<asp:Label ID="lblTotNoOfExEmp" Font-Bold="true" runat="server" Text="0" CssClass="form-label"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
private void TotalExEmpOFMonth()
{
Label lbl_TotNoOfExEmp = (Label)GrdPFRecord.FooterRow.FindControl("lblTotNoOfExEmp");
/*Sum of the Total Amount Of month*/
foreach (GridViewRow gvr in GrdPFRecord.Rows)
{
TextBox txt_NoOfExEmp = (TextBox)gvr.FindControl("txtNoOfExEmp");
lbl_TotNoOfExEmp.Text = (Convert.ToDouble(txt_NoOfExEmp.Text) + Convert.ToDouble(lbl_TotNoOfExEmp.Text)).ToString();
lbl_TotNoOfExEmp.Text = string.Format("{0:F0}", Decimal.Parse(lbl_TotNoOfExEmp.Text));
}
}
int total = 0;
protected void gvEmp_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Amount"));
}
if(e.Row.RowType==DataControlRowType.Footer)
{
Label lblamount = (Label)e.Row.FindControl("lblTotal");
lblamount.Text = total.ToString();
}
}
/*This code will use gridview sum inside data list*/
SumOFdata(grd_DataDetail);
private void SumOFEPFWages(GridView grd)
{
Label lbl_TotAmt = (Label)grd.FooterRow.FindControl("lblTotGrossW");
/*Sum of the total Amount of the day*/
foreach (GridViewRow gvr in grd.Rows)
{
Label lbl_Amount = (Label)gvr.FindControl("lblGrossS");
lbl_TotAmt.Text = (Convert.ToDouble(lbl_Amount.Text) + Convert.ToDouble(lbl_TotAmt.Text)).ToString();
}
}

row.Cells[4].Text returns nothing in GridView1_SelectedIndexChanged?

I have a GridView in my page :
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" BackColor="White"
AutoGenerateColumns="False" EmptyDataText="No data available." BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4" Width="729px" ForeColor="Black"
GridLines="Vertical" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<RowStyle BackColor="#F7F7DE" />
<Columns>
<asp:TemplateField HeaderText="TransactionKey" SortExpression="TransactionKey">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewTransactionKey" runat="server" Text='<%# Bind("TextBoxTransactionKey") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewTransactionKey" runat="server" Text='<%# Bind("TextBoxTransactionKey") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="TerminalID" SortExpression="TerminalID">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewTerminalID" runat="server" Text='<%# Bind("TextBoxTerminalID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewTerminalID" runat="server" Text='<%# Bind("TextBoxTerminalID") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="MerchantID" SortExpression="MerchantID">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewMerchantID" runat="server" Text='<%# Bind("TextBoxMerchantID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewMerchantID" runat="server" Text='<%# Bind("TextBoxMerchantID") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="شماره حساب" SortExpression="شماره حساب">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewBankAccount" runat="server" Text='<%# Bind("TextBoxBankAccount") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewBankAccount" runat="server" Text='<%# Bind("TextBoxBankAccount") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="نام بانک" SortExpression="نام بانک">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewBankName" runat="server" Text='<%# Bind("BankName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewBankName" runat="server" Text='<%# Bind("BankName") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" >
<ItemStyle Font-Size="12px" />
</asp:CommandField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<PagerStyle ForeColor="Black" HorizontalAlign="Right" BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
I set the DataSource with the follwing code :
protected void Page_Load(object sender, EventArgs e)
{
try
{
LabelTitr.Text = "Add Banks";
LabelResult.Text = "";
if (Session["Username"] != null)
{
string permission = "";
bool login = PublicMethods.CheckUsernamePass(Session["Username"].ToString(), Session["Password"].ToString(), out permission);
if (!login)
{
permission = "";
Response.Redirect("../Default.aspx");
Session["Username"] = Session["Password"] = null;
return;
}
}
else
{
Response.Redirect("../Default.aspx");
Session["Username"] = Session["Password"] = null;
return;
}
if (!IsPostBack)
BindDataToGridView1();
}
catch (Exception ex)
{
LabelResult.Text = ex.Message;
}
}
void BindDataToGridView1()
{
try
{
DataSet1 dataSet = new DataSet1();
DataClasses2DataContext dbc2 = new DataClasses2DataContext();
var Definitions = dbc2.Definitions;
if (Definitions.Count() <= 0) return;
foreach (var Definition in Definitions)
{
string bankName = dbc2.Banks.Where(c => c.BankID == Definition.BankID).First().BankName;
string CheckBox = "<input name=\"CheckBoxSubmitChanges\" type=\"checkbox\" value=" + Definition.DefinitionID + " />";
dataSet.DataTableBanks.Rows.Add(bankName, Definition.BankAccount, Definition.MerchantID, Definition.TerminalID, Definition.TerminalID);
GridView1.DataSource = dataSet.DataTableBanks;
}
GridView1.DataBind();
}
catch (Exception ex)
{
LabelResult.Text = ex.Message;
}
}
and this is GridView1_SelectedIndexChanged method :
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string temp = row.Cells[4].Text;
LabelResult.Text = temp;
}
But always temp string is empty !!!
What's wrong with it ?
Thanks
If it's a TemplateField, you have to use the FindControl("control ID") option, not the text fo the cell. I count cell 4 as being a templatefield...
There is no Text as your data is stored in controls. You need to search for the control you want and pull the Text out of.
Eg:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string temp = row.Cells[4].FindControl('LabelGridViewBankName').Text;
LabelResult.Text = temp;
}
Optionally you could could key off the DataKey property if you are using it and then use it to search your datasource for the value you want.
//this will give you control over the textbox object
var field = (TextBox)(GridView1.Rows[e.RowIndex].FindControl("your_control_ID"));
//and here you can access the text
string temp = field.Text;

Categories