NullReference Exception: when try to check a check box field in gridview - c#

I have a grid view with some check boxes. So after the grid view get updated, I am trying to see whether one particular check box is checked or not. However, I am getting an error says
Null Reference Exception was unhanded by user code
My code:
<asp:TemplateField HeaderText="FollowUp" SortExpression="FollowUp">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server"
Checked='<%# Bind("FollowUp") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkFollowup" runat="server"
Checked='<%# Bind("FollowUp") %>' Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
Code-behind file:
protected void GViewSrvcCheck_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
foreach (GridViewRow gRow in GViewSrvcCheck.Rows)
{
CheckBox fllwup = gRow.FindControl("chkFollowup") as CheckBox;
if (fllwup.Checked)//this is the one causes the error
{
}
}
}
What goes wrong here? and how can I over come this problem?

There are two possible problems:
The control couldn't be found
It wasn't a CheckBox
If you'd used a cast instead, you'd know which it was:
CheckBox followUp = (CheckBox) gRow.FindControl("chkFollowup");
It's almost always wrong to use as without a check for nullity afterwards.
I suspect the problem is that the ID actually has something to identify the row within it as well... but with the above change you'd at least be able to tell which error path you were taking.
You'll probably have to change how you find the control - but so long as "not finding the control" is an error, I think it's reasonable to leave it throwing an exception. If the control not being present is a legitimate situation, you should explicitly handle it - but otherwise, showing an error page to the user and logging the exception (e.g. with ELMAH) is fine.

Related

Import checked status from a function

I'm trying to make this code work:
<asp:CheckBox ID="statusChk" runat="server" Visible="true" Enabled="false" Checked='<%# status("de_cancel") %>'></asp:CheckBox>
What i'm trying to do is to retrieve the answer from the status function (which returns bool when i give a string) that i created in the c# source.
Doesn't give me compile error, but doesn't work. Edit: And btw, this is inside in a GridView
This works:
<asp:Label ID="lblInfo" runat="server" Visible="true" Text='<%# Bind("de_cancel") %>'></asp:Label>
But this is NOT what I'm looking for.
Sorry about my bad English.
I'm assuming that this is in a grid view, or some other repeater.
In that case, try this:
<asp:Label ID="lblInfo" runat="server" Visible="true" Text='<%# status(Eval("de_cancel")) %>'></asp:Label>
this is essentially calling your status() method and passing in the value of de_cancel
You may have to convert de_cancel inside your status method though as Eval returns an object.
Just do this in the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
//Get your string variable and use it as input here
statusChk.Checked = status("de_cancel");
}
protected bool status(string strStatus)
{
if (strStatus == "de_cancel")
{
return true;
}
else
{
return false;
}
}
This will occur when the page loads. There are other event handlers you may want to use - see http://msdn.microsoft.com/en-us/library/6w2tb12s(v=vs.90).aspx
Here is an example of how an event handler (OnSelectedIndexChanged) can be used to set a checkbox when a drop-down value is changed. As the accepted answer points out, you will need to set the AutoPostBack="true" option on the control if you want the event handler method to fire (and the page to refresh) when a control is changed:
Getting a dropdownlist to check a checkbox in asp.net/C#
Also, just looking at your code it looks like you might be using databinding, e.g. with a Repeater or ListView. In this case, please the examples for the ItemDataBound event handler below:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemdatabound(v=vs.110).aspx
http://www.codeguru.com/csharp/.net/net_asp/tutorials/article.php/c12065/ASPNET-Tip-Use-the-ItemDataBound-Event-of-a-Repeater.htm
Thanks to Darren tip, i was able to do it. Here what i did to make it work:
<asp:CheckBox ID="statusChk" runat="server" Visible="true" Enabled="false" Checked='<%#status(Convert.ToString(Eval("de_cancel")))%>'></asp:CheckBox>
Thanks everyone. ;)

Web User Control postback Issues

I am new to ASP.net thing, and i have some question regarding postback.
I have a Senario like this:
1) I have a grid on web with a panel inside.
2) I "Insert" the panel with a Web User Control by calling this
Control ctlControl;
ctlControl = LoadControl("~/UserControls/ChequeCreation.ascx");
pnlTransaction.Controls.Add(ctlControl);
3)The Web User Control providing two button. One is "update" and one is "reset".
Problem is like here:
What i wanted to achieve is when press the "update" button, it will update something back to my DB? But seem after i press the button "Update" or "Reset". The web user control is gone or missing. For my guest is because of the postback issues? Is that correct?
I tried if(!postback) still its doesn't work.
How am i going to overcome this? I already scratching my head about a day?
Thanks you so much.
Regards
LiangCk:
PS:Sorry for my english level, and please dont hesitate to voice out my error or mistake.
well you can convert any of your data columns to template column and then drag and drop your web user control to it
this will result in something like the following code check where "uc1:webUserControle1" is located in the code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDB">
<Columns>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
<uc1:webUserControle1 ID="WebUserControle1_1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
</Columns>
</asp:GridView>
if you are using AJAX, try add updatepanel on your UCT design page
ASP.NET will not preserve a dynamically added user control between postbacks. This is why it is dissapearing. You will need to add the control each time the page is created. However you will need to add it when the control tree is being initialized and restore the original control ID if you want your events to fire. These links provide a full explanation https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx and http://avinashsing.sunkur.com/2011/02/24/dynamic-controls-viewstate-and-postback/
You have to Every Time Reload the user control on Page_Init or
Page_Load. Then you can get the Button Click Event and After tha User
Control will not lost.
private void LoadUserControl(){
string controlPath = LastLoadedControl;
if (!string.IsNullOrEmpty(controlPath)) {
PlaceHolder1.Controls.Clear();
UserControl uc = (UserControl)LoadControl(controlPath);
PlaceHolder1.Controls.Add(uc);
}
}
protected void Page_Load(object sender, EventArgs e) {
LoadUserControl();
}

Converting a DBNull to boolean when binding to checkbox in a detailsview control

This is kind of silly but I have a DetailsView that binds to a record in my database using a sqlDataSource. My problem is that the field I'm binding to is a bit field, (i,e 1 or 0) that at present allows nulls. I realize this needs to change but I also need to be able to handle DBNulls on the GUI side so that the application automatically knows to set the Checked property of the checkbox to "false" if the value is DBNull. At present my template field looks like this.
</asp:TemplateField>
<asp:TemplateField HeaderText="Car:" HeaderStyle-Width="15%" ItemStyle-Width="85%">
<ItemTemplate>
<asp:Label ID="lblIsCar" runat="server" Text='<%# Eval("isCar") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="ckIsCar" runat="server" Checked='<%# Convert.ToBoolean(Eval("isCar"))%>' />
</EditItemTemplate>
</asp:TemplateField>
Everything works fine in View mode but when I click the Edit link on the details view control I get the following error:
Object cannot be cast from DBNull to other types.
Any suggestions?
Update:
I need to use 2 way binding through Bind() instead of Eval() as the details view performs an update to the selected record. If i use Convert.ToBoolean() with Bind an exception will be cast. I may end up using a CheckboxField. One would think that there would be an easy way to handle this but I have been unlucky inf finding one.
You could try a conditional to check for DBNull.Value:
Eval("isCar") == DBNull.Value ? false : Convert.ToBoolean(Eval("isCar"))

How to resolve error "Input String not in correct format"

Getting error on this line in my code:-
objGetAdd.UserAddlID = int.Parse(e.CommandArgument.ToString());
Button in aspx page:-
<asp:Button ID="btnEditAdd" Text="Edit"
CausesValidation="false" CommandName="Edit" Visible="false" runat="server" OnCommand="btnEditAdd_Click" CommandArgument='<%#Eval("UserAddID") %>/>
You do not have a CommandArgument specified in Button "btnEditAdd".
However, you are then trying to int.Parse(e.CommandArgument.ToString())
Most likely the CommandArgument is null and hence the above line will fail.
Try adding a commandArgument="1" kind of value to your button first.
EDIT: Okay, so now you've changed the code... how about doing some debugging? What's the value of e.CommandArgument at execution time? What does the generated HTML look like? What is UserAddID when generating the page? These are questions which are hard for us to determine, but should be debugging 101 for you.

Need help with error- The name 'lnk1' does not exist in the current context

This is my link button:-
<asp:LinkButton ID="lnk1" Text="Set as Default" runat="server" Visible="false" OnClick="lnk1_OnClick"></asp:LinkButton>
In Code Behind I am simply making it visible
lnk1.Visible = true;
I have checked the IDs over n over..whats wrong ? Intellisense wont detect it either..I am doing something really silly..just cant figure what it is ..help!
I even restarted Visual Studio..still same error
Is the contol part of another control template? E.G. part of a repeaters ItemTemplate etc?
Update:
Since OP has said it's part of a repeaters ItemTemplate, just thought I'd explain what to do (Even though OP has sorted it)
You need to call FindControl on the Repeater, or Controls.OfType() depending on the situation, to get the control.
ASP:
<asp:Repeater runat="server" ID="rptrTest">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtBxName" />
<asp:CheckBox runat="server" ID="chkBx1" />
<asp:CheckBox runat="server" ID="chkBx2" />
</ItemTemplate>
</asp:Repeater>
C#
IEnumerable<CheckBox> chkBoxes = rptrTest.Controls.OfType<CheckBox>();
TextBox txtBxName = (TextBox)rptrTest.FindControl("txtBxName");
What I'll often do for commonly used controls (though wether it's a good idea or not I'm sure someone will now let me know), is create a member which executes this code.
private TextBox _txtBxName;
public TextBox txtBxName {
get {
if (_txtBxName == null) {
_txtBxName = (TextBox)rptrTest.FindControl("txtBxName");
}
return _txtBxName;
}
}
Sometimes the designer class is not re-generated correctly. Things you can try:
select the line, cut, save, rebuild,
paste back, save
delete the designer
.cs file, right click the aspx,
convert to web application -> this
will generate the designer class from
scratch
Since I do not have the rights to comment; so ...
In which event you are making that item visible? try doing that in PageLoad.
Can you show your markups?
Alternatively, you can try to Find the control.

Categories

Resources