Why are my GridView bit field columns blank? - c#

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

Related

Gridview cannot parse input string is not correct

Essentially trying to capture information when a checkbox is checked off, if it is then capture the quantity inputted. Attached is the code.
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="TextboxQuantity" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Here is my aspx.cs code.
//check to see if a check box is checked
for (int row = 0; row < gv_Input.Rows.Count; row++)
{
CheckBox Cbox = (CheckBox)gv_Input.Rows[row].FindControl("CheckboxSelect");
TextBox Tbox = (TextBox)gv_Input.Rows[row].FindControl("TextboxQuantity");
int quantity = Convert.ToInt32(Tbox.Text);
if (Cbox.Checked)
{
if (Tbox == null)
{
Response.Write("<script>alert('Fill in textbox')</script>");
}
else
{
Response.Write(
"<script>alert('Something was inputted into the textbox')</script>");
}
}
}
The line that gives the error is this line
int quantity = Convert.ToInt32(Tbox.Text);
Error:
Input string was not in the correct format
Even if the text box is left blank, the test if (Tbox == null) is never going to be true because you are checking the reference to the text box, not its content. I believe that your test should be:
if(Tbox == null || string.IsNullOrWhitespace(Tbox.Text) == true) {
Through further testing. I attempted using a foreach loop and it seemed to work. Thank you for you help here is my solution
foreach (GridViewRow row in gv_Input.Rows)
{
CheckBox Cbox = (CheckBox)row.FindControl("CheckboxSelect");
TextBox Tbox = (TextBox)row.FindControl("TextboxQuantity");
if (Cbox.Checked)
{
if (Tbox.Text == null || string.IsNullOrEmpty(Tbox.Text) == true)
{
Response.Write("<script>alert('Fill in textbox')</script>");
}
else {
Response.Write("<script>alert('Successful find')</script>");
}

TemplateField in GridView Asp.Net Web Forms

I have a problem with template fields where I create a link for data in a row in Grid View. When for a first time i run my page it works fine, but later when i hide some other columns in that grid view and i want to back for my first view (I show all columns that were hidden) mine code behind throw null pointer exception. But Query for that grid is the same and the columns are the same. It always happens when i hide and add some columns to my code.
Please if u can help me with that i will be very grateful.
<asp:TemplateField HeaderText="zz" Visible="False">
<ItemTemplate>
<asp:Label ID="Label_typ" runat="server"
Text='<%# Eval("TYP") %>'></asp:Label>
<br> </br>
</ItemTemplate>
</asp:TemplateField>
Code behind witch complicates my all my code. Without it, it works fine.
if (actualYear.Equals(dd_rok22.SelectedValue))
{
int numberOfWeek = 1;
for (int i = Convert.ToInt32(actualMonth); i <= 12; i++)
{
GRID_VIEW_MAKRO.Columns[i + 7].Visible = false;
if (i == Convert.ToInt32(actualMonth))
{
int numberColumnActual = i;
BoundField field2 = new BoundField();
GRID_VIEW_MAKRO.Columns.Insert(numberColumnActual + 3, field2);
for (int j = 1; j <= weekNumberActualMonth; j++)
{
BoundField field = new BoundField();
GRID_VIEW_MAKRO.Columns.Insert(numberColumnActual + 3, field);
field.HeaderText = "M" + actualMonth + "_T" + numberOfWeek;
field.DataFormatString = "{0:###,###}";
numberColumnActual++;
numberOfWeek++;
}
for (int numberOfWeekPrevious = numberOfWeek; numberOfWeekPrevious <= 4; numberOfWeekPrevious++)
{
BoundField field = new BoundField();
GRID_VIEW_MAKRO.Columns.Insert(numberColumnActual + 2, field);
field.HeaderText = "M" + previousMonth2 + "_T" + numberOfWeek;
field.DataFormatString = "{0:###,###}";
numberOfWeek++;
numberColumnActual++;
}
}
}
}
And the exception shows when i create Label witch have null value because of TemplateField have null value.
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string mregion= DataBinder.Eval(e.Row.DataItem, "MAKRO_NAME").ToString();
Label lbl = (Label)e.Row.FindControl("Label_typ");
string CellValue = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ROK"));
//it cannot Trim me null value..
string ID = lbl2.Text.Trim() + '_' + lbl3.Text.Trim();
e.Row.Attributes.Add("onclick", "top.location.href='report_se.aspx?nazwa=" + ID + "&ye=" + CellValue + "';");
}
}
1) Making some field visible false should not create any error at the run time.
2) For null pointer exception, I think you are trying to typecast null values. If any of your fields contain null values then it is advisable to check it before typecasting it.

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 Footer row is null

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">

Changing selection for a DropdownList triggers OnSelectedIndexChanged event of a CheckBoxList

Basically I want to implement a filtering option for a Grid view and I have a dropdown list containing the column names and a checkboxlist containing the available filtering values for that column. Every time I select a different column, I have to load the filtering values for that column into the checkbox list.
The problem I have is that when I change the column in the dropdown list, the event for the checklist is fired and the application crashes.
My controls are defined like this:
<div class="LeftAligned">
<asp:Label ID="FilterLabel" runat="server" Text="Filter by:" />
<asp:DropDownList runat="server" ID="FilterReviewsDropDownList" AutoPostBack="true" OnSelectedIndexChanged="FilterReviewsDropDownList_SelectedIndexChanged" />
<asp:ImageButton ID="FilterReviewsButton" runat="server" ImageUrl="~/images/filter.png" AlternateText="VALUE" CssClass="filter_button" OnClick="FilterReviewsButton_Click" />
<div onmouseout="javascript:bMouseOver=false;" onmouseover="javascript:bMouseOver=true;" class="filter_div">
<asp:CheckBoxList AutoPostBack="true" ID="FilterReviewsCheckBoxList" ClientIDMode="Static" runat="server" CssClass="filter_checklist collapsed"
OnSelectedIndexChanged="FilterReviewsCheckBoxList_Selected">
</asp:CheckBoxList>
</div>
<%--asp:Button runat="server" ID="ApplyFilterButton" Text="Apply Filter" OnClick="ApplyFilterButton_Click"/>
<asp:Button runat="server" ID="ClearFilterButton" Text="Clear Filter" OnClick="ClearFilterButton_Click"/--%>
</div>
In the CodeBehind file I have the following code:
protected void FilterReviewsButton_Click(object sender, EventArgs e)
{
FilterReviewsCheckBoxList.CssClass = "filter_checklist";
}
protected void FilterReviewsDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
LoadFilterCheckboxes(FilterReviewsDropDownList.SelectedIndex);
}
private void LoadFilterCheckboxes(int iColumn)
{
SortedSet<string> oItems = new SortedSet<string>();
for (int i = 0; i < ReviewsGridView.Rows.Count; i++)
{
IEnumerable<Label> oLabels = ReviewsGridView.Rows[i].Cells[iColumn].Controls.OfType<Label>();
string sValue = "";
if (oLabels != null && oLabels.Count() > 0)
{
sValue = oLabels.First().Text;
}
else
{
sValue = ReviewsGridView.Rows[i].Cells[iColumn].Text;
}
if (!oItems.Contains(sValue))
oItems.Add(sValue);
}
FilterReviewsCheckBoxList.Items.Clear();
FilterReviewsCheckBoxList.Items.Add("All");
FilterReviewsCheckBoxList.Items[0].Selected = true;
foreach (string sItem in oItems)
{
FilterReviewsCheckBoxList.Items.Add(sItem);
FilterReviewsCheckBoxList.Items[FilterReviewsCheckBoxList.Items.Count - 1].Selected = true;
}
}
protected void FilterReviewsCheckBoxList_Selected(object sender, EventArgs e)
{
string sResult = Request.Form["__EVENTTARGET"];
if (string.IsNullOrEmpty(sResult))
{
FilterReviewsCheckBoxList.Items[0].Selected = true; //weird bug fix...
return;
}
string[] sCheckedBox = sResult.Split('$');
//get the index of the item that was checked/unchecked
int i = int.Parse(sCheckedBox[sCheckedBox.Length - 1].Split('_')[1]);
if (i == 0)
{
if (FilterReviewsCheckBoxList.Items[i].Selected == true)
{
for (int j = 1; j < FilterReviewsCheckBoxList.Items.Count; j++)
FilterReviewsCheckBoxList.Items[j].Selected = true;
}
else
{
for (int j = 1; j < FilterReviewsCheckBoxList.Items.Count; j++)
FilterReviewsCheckBoxList.Items[j].Selected = false;
}
}
else
{
if (FilterReviewsCheckBoxList.Items[i].Selected == false)
{
FilterReviewsCheckBoxList.Items[0].Selected = false;
}
else
{
//if (oFirstTable != null)
//{
// oTable = oFirstTable;
// oView = oTable.DefaultView;
//}
bool bAllChecked = true;
for (int j = 1; j < FilterReviewsCheckBoxList.Items.Count; j++)
{
if (FilterReviewsCheckBoxList.Items[j].Selected == false)
{
bAllChecked = false;
break;
}
}
if (bAllChecked)
FilterReviewsCheckBoxList.Items[0].Selected = true;
}
}
}
Any idea of why FilterReviewsCheckBoxList_Selected is called (with the dropdownlist as the sender argument) when changing the dropdown list?
For anyone who may encounter the same problem, the fix is to avoid static binding of the grid view to entity data source. Instead, bind the grid dynamically in the page load event.

Categories

Resources