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.
Related
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>");
}
Currently I try to use Repeater WebControl in order to display a table that list out all possible component. Below is my table;
Right now I try to merged cells in Group Code and Group Description column that have the same value. Below is my merging cell code, noted that the code is in class;
public void repeaterRowSpan(string repeaterID, string columnID)
{
var pageHandler = HttpContext.Current.CurrentHandler;
Control ctrl = ((Page)pageHandler).Master.FindControl("ContentPlaceHolder3").FindControl(repeaterID);
Repeater repeaterName = (Repeater)ctrl;
for (int i = repeaterName.Items.Count - 1; i > 0; i--)
{
HtmlTableCell oCell_previous = (HtmlTableCell)repeaterName.Items[i - 1].FindControl(columnID);
HtmlTableCell oCell = (HtmlTableCell)repeaterName.Items[i].FindControl(columnID);
oCell.RowSpan = (oCell.RowSpan == -1) ? 1 : oCell.RowSpan;
oCell_previous.RowSpan = (oCell_previous.RowSpan == -1) ? 1 : oCell_previous.RowSpan;
if (oCell.InnerText == oCell_previous.InnerText)
{
oCell.InnerText = "";
oCell_previous.RowSpan += oCell.RowSpan;
}
}
}
Somehow the code manage to delete the same value in the column but maintain the rowspan. When I debugged, the oCell_previous.RowSpan return '2' so the code itself working fine. Below is the result of merging;
How can I modified my code in such way it will merged the cell?
In your opinion, between Repeater and GridView which is most suitable to show data in table form in this project? In my understanding, Repeater is most suitable since it faster than GridView. GridView is only suitable if you have edit function to go with your table.
This can be implemented using the OnDataBound event. The OnDataBound event of the GridView is executed after the GridView is populated with the records. Executed a loop in reverse over the GridView Rows and then the common Cells are identified and merged into single cell.
Below sample code merges the first & second columns (assuming that there are redundant values by comparing the above row(s)),
Feel free to leave a comment if you need more info.
protected void OnDataBound(object sender, EventArgs e)
{
for (int i = GridView1.Rows.Count - 1; i > 0; i--)
{
GridViewRow row = GridView1.Rows[i];
GridViewRow previousRow = GridView1.Rows[i - 1];
for (int j = 0; j < row.Cells.Count; j++)
{
if (row.Cells[j].Text == previousRow.Cells[j].Text)
{
if (previousRow.Cells[j].RowSpan == 0)
{
if (row.Cells[j].RowSpan == 0)
{
previousRow.Cells[j].RowSpan += 2;
}
else
{
previousRow.Cells[j].RowSpan = row.Cells[j].RowSpan + 1;
}
row.Cells[j].Visible = false;
}
}
}
}
}
i have created a telerik grid for small payment module
in this module i have selected two checkbox and enter a amount,i need the total amount to be displayed in the donation amount label
The current code is to sum up the values displayed in the second column,and saving the values in session and passsing to next page.
Gridview
<telerik:GridTemplateColumn FilterControlAltText="Filter TemplateColumn3 column" UniqueName="TemplateColumn3">
<ItemTemplate>
<asp:TextBox ID="txt_amnt" runat="server"></asp:TextBox> </td>
</ItemTemplate>
</telerik:GridTemplateColumn>
c# code
protected void chk_box_CheckedChanged(object sender, EventArgs e)
{
if (ViewState["dt"].ToString().Trim() != "NULL")
{
dt = (DataTable)ViewState["dt"];
}
if (dt.Columns.Count == 0)
{
dt.Columns.Add("Id");
dt.Columns.Add("Name");
dt.Columns.Add("Amount");
}
CheckBox chk = (CheckBox)sender;
if (chk.Checked == true)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count-1 ]["Id"] = ((Label)chk.FindControl("lb_id")).Text.Trim();
dt.Rows[dt.Rows.Count - 1]["Name"] = ((Label)chk.FindControl("lb_donation")).Text.Trim();
dt.Rows[dt.Rows.Count - 1]["Amount"] = ((Label)chk.FindControl("lb_amount")).Text.Trim();
// dt.Rows[dt.Rows.Count + 1]["chkstatus"] = ((Label)chk.FindControl("lb_amount")).ToString().Trim();
}
else {
for (int i = 0; i < dt.Rows.Count; i++)
{
if(((Label)chk.FindControl("lb_id")).Text.Trim()==dt.Rows[i]["Id"].ToString().Trim())
{ dt.Rows.RemoveAt(i); }
}
}
ViewState["dt"] = dt;
double tamount = 0;
for (int i2 = 0; i2 < dt.Rows.Count; i2++)
{
tamount = tamount + Convert.ToDouble(dt.Rows[i2]["Amount"]);
}
lb_tamount.Text = tamount.ToString() ;
}
I believe your code for the CheckBox will always hit error.
How can you find a control inside a CheckBox ? Secondly your code is not complete as per the result you are showing. Anyway here is the idea how you can get checked item in your RadGrid.
First you need loop the RadGrid to get all checked CheckBox.
Then sum up the total and put it to the label.
This code just to mock up for your scenario. Please use TryParse to get the int value to ensure no converting error.
Code Behind
protected void chkCheck_CheckedChanged(object sender, EventArgs e)
{
// Variable
int total = 0;
int amt = 0;
int donateAmt = 0;
foreach (GridDataItem item in rg.Items)
{
// Find Control
CheckBox chkCheck = item.FindControl("chkCheck") as CheckBox;
Label lblAmount = item.FindControl("lblAmount") as Label;
TextBox txtAmount = item.FindControl("txtAmount") as TextBox;
// Reset Amount
amt = 0;
donateAmt = 0;
// Check
if (chkCheck != null && chkCheck.Checked)
{
// Check & Get Value
if (lblAmount != null && txtAmount != null)
{
// Check & Set
if (lblAmount.Text.Trim() != string.Empty)
amt = Convert.ToInt32(lblAmount.Text.Trim());
// Check & Set
if (txtAmount.Text != string.Empty)
donateAmt = Convert.ToInt32(txtAmount.Text.Trim());
// Check current Amount in stock and donate amt
if (donateAmt > amt)
{
donateAmt = amt;
txtAmount.Text = donateAmt + "";
}
// Reset to the text
}
total += donateAmt;
}
}
lblTotal.Text = total + "";
}
I have list of hyperlinks which i want to use to create a 2x* table (* is number of hyperlinks)
Here is my code...
for (int rows = 0; rows < hlist.Count; rows++) //Create rows for the number of hyperlinks, so i will always have a spare row.
{
TableRow row = new TableRow(); // Create the new rows
table.Rows.Add(row); //Add rows to the table
for (int cells = 0; cells < 2; cells++)
{
TableCell cell = new TableCell();
for(int h = 0; h < hlist.Count; h++)
cell.Controls.Add(hlist[h]);
row.Cells.Add(cell);
}
}
All this does is list all my hyperlinks in a single column table, with a new row for each hyperlink!
Any help would be appreciated!!
Thanks
Assuming that you want to create a table that shows two hyperlinks per row, you could try the following code:
for (int i = 0; i < hlist.Count; i += 2)
{
TableRow row = new TableRow(); // Create the new rows
table.Rows.Add(row);
for (int j = i; j < Math.Min(i + 2, hlist.Count); j++)
{
TableCell cell = new TableCell();
cell.Controls.Add(hlist[j]);
row.Controls.Add(cell);
}
}
However, using dynamically added controls in ASP.NET is complex if you want them to react on events. So I'd propose to check whether you could change your approach so that you can use a Repeater instead. In order to do so, you'd first have to change your data model, e.g. to a list of Pair objects that contain two URLs, e.g.:
public void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
IEnumerable<Uri> uris = GetUris();
List<Tuple<Uri, Uri>> pairs = new List<Tuple<Uri, Uri>>();
for (int i = 0; i < uris.Count; i += 2)
{
var uri1 = uris[i];
var uri2 = i + 1 < uris.Count ? uris[i + 1] : null;
pairs.Add(new Tuple<Uri, Uri>(uri1, uri2));
}
rpt.DataSource = pairs;
rpt.DataBind();
}
}
If your URLs are not compatible with a Uri (maybe they contain a leading ~), you can also use strings instead of Uri.
The markup for your the Repeater would look similar to this:
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:HyperLink runat="server" Text="Link 1"
NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "Item1") %>' />
</td>
<td>
<asp:HyperLink runat="server" Text="Link 1"
NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "Item2") %>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
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