GridView Footer row is null - c#

Footer is set to visible and I can see it's being created. However when total (table sums) are passed over to it, there's error indicating GridView2.FooterRow is null...
totTable refers to a DataTable carrying totals.
aspx:
ShowHeader="true" ShowFooter="true" FooterStyle-CssClass="FooterStyle"
cs:
DataRow dr = totTable.Rows[0];
foreach (DataControlField col in GridView2.Columns)
{
foreach (DataColumn dc in totTable.Columns)
{
int i = GridView2.Columns.IndexOf(col);
GridView2.FooterRow.Cells[i].Text = dr[i].ToString();
}
}
What's the root cause behind this?

use following code after binding gridview:
public void CountGrandTotal()
{
int sum = 0;
for (int i = 0; i <grdproduct.Rows.Count ; i++)
{
Label lblprice = (Label)grdproduct.Rows[i].FindControl("Label5");
sum += int.Parse(lblprice.Text);
}
Label lblgtotal = (Label)grdproduct.FooterRow.FindControl("Label7");
lblgtotal.Text = sum.ToString();

Add the footer on the OnLoad method of the GridView.
<asp:GridView ID="Gv"
runat="server"
ShowFooter="true"
OnLoad="Gv_Load">

Related

Two Columns with same header text in gridview in c#

I am having a gridview in which I don't want to display Header Text for two columns and two columns should have same header name (INFA). Gridview Looks Like:
<asp:GridView ID="GridView6" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="DayOfWeek" HeaderText="" ItemStyle-Width="30" />
<asp:BoundField DataField="DateOfMonth" HeaderText="" ItemStyle-Width="30" />
<asp:BoundField DataField="Emp_Name" HeaderText="INFA" ItemStyle-Width="30" />
<asp:BoundField DataField="Group_Name" HeaderText="INFA" ItemStyle-Width="30" />
<asp:BoundField DataField="Emp_Id" HeaderText="Mainframe" ItemStyle-Width="30" />
</Columns>
</asp:GridView>
I need to flip this gridview and make rows into columns and columns into rows. The logic was working fine when I had different names in Header Text for all DataFields. But in my requirement I don't need a Header text for two columns and two columns must have same header text (As shown above in Gridview). When I run my logic with no column name as shown above I get this error:
Exception Details: System.Data.DuplicateNameException: A column named ' ' already belongs to this DataTable.
My logic is:
protected void btnConvert_Data()
{
System.Data.DataTable dt = new System.Data.DataTable("GridView_Data");
foreach (TableCell cell in GridView6.HeaderRow.Cells)
{
if (cell.Text == "")
{
dt.Columns.Add("");
}
else
{
dt.Columns.Add(cell.Text);
}
}
dt.Rows.Add("IST Hours");
//dt.Rows.Add("8:45AM-6PM");
foreach (GridViewRow row in GridView6.Rows)
{
dt.Rows.Add();
for (int i = 0; i < row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;
}
}
gvColumnsAsRows.DataSource = FlipDataTable(dt);
gvColumnsAsRows.DataBind();
gvColumnsAsRows.HeaderRow.Visible = false;
}
To flip rows into columns and vice versa:
public static System.Data.DataTable FlipDataTable(System.Data.DataTable dt)
{
System.Data.DataTable table = new System.Data.DataTable();
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
table.Columns.Add(Convert.ToString(i));
}
DataRow dr;
//get all the columns and make it as rows
for (int j = 0; j < dt.Columns.Count; j++)
{
dr = table.NewRow();
dr[0] = dt.Columns[j].ToString();
for (int k = 1; k <= dt.Rows.Count; k++)
dr[k] = dt.Rows[k - 1][j];
table.Rows.Add(dr);
}
return table;
}
I am getting the above mentioned error in btnConvert_Data() on line dt.Columns.Add(cell.Text);. Can anyone please help me with this issue?
My final Output when I flip the Gridview should look like this:
column header text and column name are different, which column name must be unique in a DataTable.
so for you instance, you can specify a different random name to the columns which have no column header text
and also, you need to detect if the Header is real string.Empty or something just looks like empty, in your case, the header text is never an empty value, it's
so your logic will never hit, i mean cell.Text=="" will always returns false
so here is the solution
foreach (TableCell cell in GridView6.HeaderRow.Cells)
{
if (cell.Text == " ")
{
dt.Columns.Add(Guid.NewGuid().ToString()); //just some random value, i use guid, you can use anything you like to keep it unique.
}
else
{
dt.Columns.Add(cell.Text);
}
}
You need to make sure that every column has a unique name. You can do that by checking if the column name exists and if so make it a unique one by adding the index to the column name.
for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
{
string cellText = GridView1.HeaderRow.Cells[i].Text;
//check if the column name exists and if so make it unique
if (dt.Columns.Contains(cellText))
{
dt.Columns.Add(cellText + "_" + i);
}
else
{
dt.Columns.Add(cellText);
}
}

Gridview get Checkbox.Checked value

I have a GridView that has 10 columns populated by CheckBoxes. But instead of using FindControl() is there a way to get the CheckBox.Checked value by using a loop?
Current Code:
if (e.CommandName == "updaterow")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
// TableCell BranchCode = selectedRow.Cells[0];
CheckBox cb101 = (CheckBox)selectedRow.FindControl("cb101");
CheckBox cb102 = (CheckBox)selectedRow.FindControl("cb102");
//...and so on
}
ASPX CODE:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="101">
<ItemTemplate>
<asp:CheckBox runat="server" id="cb101" AutoPostBack="false" Checked='<%# Eval("101").ToString()=="1" ? true : false %>' Enabled='<%#(String.IsNullOrEmpty(Eval("101").ToString()) ? false: true) %>'/>
</ItemTemplate>
</asp:TemplateField>
....and so on
<asp:ButtonField ButtonType="Button" CommandName="updaterow" Text="Update"/>
</Columns>
</asp:GridView>
Try this,
Using foreach Loop:
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
if (chk != null && chk.Checked)
{
// ...
}
}
Use it in OnRowCommand event and get checked CheckBox value.
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int requisitionId = Convert.ToInt32(e.CommandArgument);
CheckBox cbox = (CheckBox)row.Cells[3].Controls[0];
For run all lines of GridView don't use for loop, use foreach loop like:
foreach (GridViewRow row in yourGridName.Rows) //Running all lines of grid
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
//if checked do something
}
}
}
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkbox = (CheckBox)row.FindControl("CheckBox1");
if (chkbox.Checked == true)
{
// Your Code
}
}
If you want a method other than findcontrol try the following:
GridViewRow row = Gridview1.SelectedRow;
int CustomerId = int.parse(row.Cells[0].Text);// to get the column value
CheckBox checkbox1= row.Cells[0].Controls[0] as CheckBox; // you can access the controls like this
foreach (DataRow row in DataRow row in GridView1.Rows)
{
foreach (DataColumn c in GridView1.Columns)
bool ckbVal = (bool)(row[c.ColumnName]);
}
Blockquote
foreach (GridViewRow row in tempGrid.Rows)
{
dt.Rows.Add();
for (int i = 0; i < row.Controls.Count; i++)
{
Control control = row.Controls[i];
if (control.Controls.Count==1)
{
CheckBox chk = row.Cells[i].Controls[0] as CheckBox;
if (chk != null && chk.Checked)
{
dt.Rows[dt.Rows.Count - 1][i] = "True";
}
else
dt.Rows[dt.Rows.Count - 1][i] = "False";
}
else
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text.Replace(" ", "");
}
}
You want an independent for loop for all the rows in grid view, then refer the below link
http://nikhilsreeni.wordpress.com/asp-net/checkbox/
Select all checkbox in Gridview
CheckBox cb = default(CheckBox);
for (int i = 0; i <= grdforumcomments.Rows.Count – 1; i++)
{
cb = (CheckBox)grdforumcomments.Rows[i].Cells[0].FindControl(“cbSel”);
cb.Checked = ((CheckBox)sender).Checked;
}
Select checked rows to a dataset; For gridview multiple edit
CheckBox cb = default(CheckBox);
foreach (GridViewRow row in grdforumcomments.Rows)
{
cb = (CheckBox)row.FindControl("cbsel");
if (cb.Checked)
{
drArticleCommentsUpdates = dtArticleCommentsUpdates.NewRow();
drArticleCommentsUpdates["Id"] = dgItem.Cells[0].Text;
drArticleCommentsUpdates["Date"] = System.DateTime.Now;dtArticleCommentsUpdates.Rows.Add(drArticleCommentsUpdates);
}
}

Why are my GridView bit field columns blank?

I have an issue when displaying bit fields in a GridView, when the GridView is rendered the bit field is blank.
Code to bind to my GridView:
protected void InitGridViewDisplay(GridView mygrid, Button mybutton, DataTable mydt, int i)
{
mygrid.DataSource = mydt;
mygrid.DataBind();
mygrid.Visible = true;
}
All other fields display correctly, but, the bit fields show as empty columns?
...after further discussion...
for (int j = 0; j < mydt.Columns.Count; j++)
{
string fieldtype = Convert.ToString(mydt.Columns[j].DataType);
if (fieldtype == "System.Boolean")
{
foreach (DataRow row in mydt.Rows)
{
string getrowvalue = Convert.ToString(row[j]);
switch (getrowvalue)
{
case "False":
{
row[j] = 0;
break;
}
case "True":
{
row[j] = 1;
break;
}
}
}
}
}
...Am I missing something? Columns is still blank when displayed in the GridView...
In my project I have a GridView with checkboxs. It checks and unchecks using a "Bit" value.
<Columns>
<ItemTemplate>
<asp:CheckBox id="chkStatus" Enabled='<%# Enable(Eval("Status")) %>' runat="server" />
</ItemTemplate>
At code behind
Protected Function Enable(ByVal sStatus As Boolean) As String
If UCase(Trim(sStatus)) = True Then
Return "true"
ElseIf UCase(Trim(sStatus)) = False Then
Return "false"
End If
End Function
Arun

How to make a customized GridView that is completely user defined

I have a GridView:
On Button_Click
I want the first column of my GridView with the items of ListBox1 and 2nd column with the EDIT link and from 3rd column on wards I want the headers as the items of ListBox2.
So far I am able to achieve EDIT link in the 2nd column and from 3rd column on wards the headers of the GridView with ListBox2 items.
Now I want ListBox1 items as the first column of my GridView. I have attached an image with show what exactly I want and what I have achieved so far.
Kindly help me on. Thank you.
The .cs code I have designed is:
DataTable dt = new DataTable();
DataRow rw = default(DataRow);
for (int i = 0; i < ListBox3.Items.Count; i++)
{ dt.Columns.Add(ListBox3.Items[i].ToString(),System.Type.GetType("System.String"));
}
for (int j = 0; j < count; j++)
{
rw = dt.NewRow();
for (int i = 0; i < ListBox3.Items.Count; i++)
{
rw[ListBox3.Items[i].ToString()] = " ";
}
dt.Rows.Add(rw);
}
GridView2.DataSource = dt;
GridView2.DataBind();
The asp code for GridView is :
<Columns>
<asp:TemplateField HeaderText="Locations">
<ItemTemplate>
<asp:Label ID="Lab1" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
First create a event of your gridview_RowDataBound
and change value of your label
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl1= ((Label)e.Row.FindControl("Lab1"));
lbl1.text = ListBox1.items[e.Row.RowIndex].ToString();
}
}

Total of Selected Items in Gridview

I have a Gridview
I have Click Button and two labels. (Risk_label and MV_label)
Risk and MV column has price value.
My Checkbox column names are NameCheckBoxField1 and NameCheckBoxField2
How can i calculate only "Which i selected in Gridview" Risk total and MV total in my labels?
Example;
Risk (Checked rows) --> 10, 20, 30 ---> Risk_label = 60
MV (Checked rows) --> 20, 30, 40 ---> MV_label = 90
EDİT: I try this code;
double sum = 0;
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox cb = (CheckBox)gvr.FindControl("NameCheckBoxField1");
if (cb.Checked)
{
double amount = Convert.ToDouble(gvr.Cells[1].Text);
sum += amount;
}
}
Risk_label.Text = sum.ToString();
But i getting an error.
protected void CalculateButton_Click(object sender, EventArgs e)
{
Int32 totalMVValue = 0, totalRiskValue = 0;
// Iterate through the Products.Rows property
foreach (GridViewRow row in GridView1.Rows)
{
// Access the CheckBox
CheckBox mvSelectorCheckBox = (CheckBox)row.FindControl("MVSelector");
if (mvSelectorCheckBox != null && mvSelectorCheckBox.Checked)
{
// First, get the primaryId for the selected row
int mvValue=
Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
totalMVValue += mvValue;
}
CheckBox riskSelectorCheckBox = (CheckBox)row.FindControl("RiskSelector");
if (riskSelectorCheckBox != null && riskSelectorCheckBox.Checked)
{
// First, get the primaryId for the selected row
int riskValue =
Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
totalRiskValue += riskValue;
}
}
}
Looking at your last comment:
<asp:templatefield headertext=""> <itemtemplate> <asp:CheckBox DataField="NameCheckBoxField1" Checked="True" runat="server"></asp:CheckBox> </itemtemplate> </asp:templatefield>
Is DataField assigned NameCheckBoxField1? Or is it a typo?
It should be ID="NameCheckBoxField1"
I think jQuery would be the best option for you.
1. Add classes for Risk_Label and MV_Label
2. On checkbox click get the value of Risk_Label and MV_Label of the same row using the classes.
3. If it is checked then add value other wise subtract values.
$('.mygrid :checkbox').click(function () {
var amt = parseFloat($(this).parents('tr').find('.ClassRisk_label').text());
//One Fee Case
if (!isNaN(amt)) {
if ($(this).is(':checked')) {
totalAmt = totalAmt + amt;
}
else {
totalAmt = totalAmt - amt;
}
}
//Show the value...
});

Categories

Resources