Showing posts with label controls. Show all posts
Showing posts with label controls. Show all posts

Thursday, March 29, 2012

Object reference error

I have a datagrid and each column contains a different controls. When Iam trying to access the value of the ListBox controls inside thedatagrid it keeps on throwing "Object reference not set to an instanceof an object". The line is bold where it throws the error.
Here is my code:
private void Button1_Click(object sender, System.EventArgs e)
{
StringBuilder str = new StringBuilder();

foreach(DataGridItem dgi in myDataGrid.Items)
{
TextBox myTextBox = (TextBox)(dgi.Cells[0].Controls[1]);
ListBox myListBox = (ListBox)(dgi.Cells[1].Controls[1]);
DropDownList myList = (DropDownList)(dgi.Cells[2].Controls[1]);
CheckBox myCheckBox = (CheckBox)(dgi.Cells[3].Controls[1]);
str.Append(myTextBox.Text);
if(myListBox.SelectedItem.Value != null)
{
str.Append(myListBox.SelectedItem.Text);
}


str.Append(myList.SelectedItem.Text);
str.Append(myCheckBox.Checked);


}

Probably my eyes but there's no line in bold.

If you debug and check the type of the controls that you're using, are they of the correct type? I know I had some trouble in the past that sometimes I had to take Controls[0] and sometimes Controls[1] to obtain the correct control.

Grz, Kris.


Yeah I tried using Controls[0] but it did not worked and gave me that "Specific cast is not valid" error. The bold line below causes "Object reference not set to an instance of an object" This error is only thrown when I dont select any item in the ListBox.

foreach(DataGridItem dgiin myDataGrid.Items)

{

TextBox myTextBox = (TextBox) (dgi.Cells[0].Controls[1]);

ListBox myListBox = (ListBox) (dgi.Cells[1].Controls[1]);

DropDownList myList = (DropDownList) (dgi.Cells[2].Controls[1]);

CheckBox myCheckBox = (CheckBox) (dgi.Cells[3].Controls[1]);

str.Append(myTextBox.Text);

if(myListBox.SelectedItem.Value !=null)

{

str.Append(myListBox.SelectedItem.Text);

}

str.Append(myList.SelectedItem.Text);

str.Append(myCheckBox.Checked);

}


Okay I got it. I had to get the value from the ListBox into a string variable and than compare the string to null and empty.
The following code works:
foreach(DataGridItem dgi in myDataGrid.Items)
{
TextBox myTextBox = (TextBox)(dgi.Cells[0].Controls[1]);
ListBox myListBox = (ListBox)(dgi.Cells[1].Controls[1]);
DropDownList myList = (DropDownList)(dgi.Cells[2].Controls[1]);
CheckBox myCheckBox = (CheckBox)(dgi.Cells[3].Controls[1]);
str.Append(myTextBox.Text);
string a = myListBox.SelectedValue;
//string b = myListBox.SelectedItem.Value;
//string c = myListBox.SelectedItem.Text;
if(a != null && a != "")
{
str.Append(myListBox.SelectedItem.Text);
}


str.Append(myList.SelectedItem.Text);
str.Append(myCheckBox.Checked);


}

Monday, March 26, 2012

Object reference not set to an instance of an object

I have the following code where I am extracting data from a set of controls for an xml class. I iterate through my controls and pull my control id and selected value for radiobuttonlist or checkboxlist. I am successfully iterating through my controls and can display the result set (surveylabel1). When I add the code to add detail items to my responsedataset i get an error "Object reference not set to an instance of an object."

I am using the integer i in my iteration and to define the detail, is the variable i not available inside of my Case statement, or do I have another problem with my code?

Thank you.


Private Function ExtractResults() As SResponse.Schema7Ihsurveyresponse

Dim currentUser As New AccBusiness.User( _
CType(Context.User, SitePrincipal))

Dim sb As StringBuilder = New StringBuilder
sb.Append("Answers: ")
Dim msgtext As String
Dim ctrl, ctl2 As Control
Dim rb As RadioButtonList
Dim lb As TextBox
Dim ck As CheckBoxList

Dim i As Integer
Dim id As Integer
Dim item As ListItem
Dim newResponse As New SResponse.Schema7Ihsurveyresponse

newResponse.surveyid = 1
newResponse.Userid = currentUser.UserId

For i = 0 To (Controls().Count - 1)
Dim newresponsedetail(i) As SResponse.Schema7IhsurveyresponseIhsresponsedetail
ctrl = Controls(i)
id = -1

Select Case ctrl.GetType.Name
Case "RadioButtonList"

rb = CType(ctrl, RadioButtonList)

sb.Append(rb.ID & ": " & rb.SelectedValue)

newresponsedetail(i).question = rb.ID.ToString
newresponsedetail(i).result = CInt(rb.SelectedValue)

Case "CheckBoxList"
ck = CType(ctrl, CheckBoxList)

For Each item In ck.Items
If item.Selected Then
sb.Append(ck.ID & ": ")
sb.Append(item.Value & ", ")
'newresponsedetail(i).question = ck.ID.ToString
'newresponsedetail(i).result = CInt(item.Value)
End If

Next

End Select
sb.Append(" - ")

Next
Surveylabel1.Text = sb.ToString
End Function

Hi,
i couldn't find "responsedataset" in ur code ?
I am sorry I should have been clearer in my question. I am trying to iterate through my controls adding the Control.id and control.selectedvalue to the detail of my sresponse.schema7idsurveyresponse (please forgive the long names - I plan to clean this up later).

I have alltered my code for ExtractResults() from my previous post and add the code for my sresponse class.

I commented out my execute scalar and set my return for my Addresponse (newresponse) function to be the XMLResoponse string for troubleshooting. Although I am not getting any errors, I am also not getting any XMLResponse string. Why would that be? What am I missing?

 Private Function ExtractResults() As SResponse.Schema7Ihsurveyresponse

Dim currentUser As New AccBusiness.User( _
CType(Context.User, SitePrincipal))

Dim sb As StringBuilder = New StringBuilder
sb.Append("Answers: ")
Dim msgtext As String
Dim ctrl, ctl2 As Control
Dim rb As RadioButtonList
Dim lb As TextBox
Dim ck As CheckBoxList

Dim i As Integer
Dim id As Integer = (Controls().Count - 1)
Dim item As ListItem
Dim newResponse As New SResponse.Schema7Ihsurveyresponse

newResponse.surveyid = 1
'newResponse.Userid = currentUser.UserId
newResponse.Userid = 1

Dim details(id) As SResponse.Schema7IhsurveyresponseIhsresponsedetail

For i = 0 To (Controls().Count - 1)
details(i) = New SResponse.Schema7IhsurveyresponseIhsresponsedetail

ctrl = Controls(i)
id = -1

Select Case ctrl.GetType.Name
Case "RadioButtonList"

rb = CType(ctrl, RadioButtonList)

sb.Append(rb.ID & ": " & rb.SelectedValue)

details(i).question = rb.ID.ToString
'details(i).result = CInt(rb.SelectedValue)

details(i).result = 1

Case "CheckBoxList"
ck = CType(ctrl, CheckBoxList)

For Each item In ck.Items
If item.Selected Then
sb.Append(ck.ID & ": ")
sb.Append(item.Value & ", ")
details(i).question = ck.ID.ToString
'details(i).result = CInt(item.Value)
details(i).result = 2
End If

Next

End Select
sb.Append(" - ")
Next
newResponse.ihsresponsedetail = details
Dim responseID As String = SResponse.addresponse(newResponse)

Surveylabel1.Text = "Response: " & responseID & sb.ToString
End Function
Private Sub btnSurveySubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSurveySubmit.Click
ExtractResults()

End Sub

End Class

my sresponse class:


<System.Xml.Serialization.XmlRootAttribute([Namespace]:="", IsNullable:=False)> _
Public Class Schema7

'<remarks/>
<System.Xml.Serialization.XmlElementAttribute("ihsurveyresponse", Form:=System.Xml.Schema.XmlSchemaForm.Unqualified)> _
Public Items() As Schema7Ihsurveyresponse
End Class

'<remarks/>
Public Class Schema7Ihsurveyresponse

'<remarks/>
<System.Xml.Serialization.XmlElementAttribute("ihsresponsedetail", Form:=System.Xml.Schema.XmlSchemaForm.Unqualified)> _
Public ihsresponsedetail() As Schema7IhsurveyresponseIhsresponsedetail

'<remarks/>
<System.Xml.Serialization.XmlAttributeAttribute()> _
Public surveyid As Integer

'<remarks/>
<System.Xml.Serialization.XmlIgnoreAttribute()> _
Public surveyidSpecified As Boolean

'<remarks/>
<System.Xml.Serialization.XmlAttributeAttribute()> _
Public Userid As Integer

'<remarks/>
<System.Xml.Serialization.XmlIgnoreAttribute()> _
Public UseridSpecified As Boolean
End Class

'<remarks/>
Public Class Schema7IhsurveyresponseIhsresponsedetail

'<remarks/>
<System.Xml.Serialization.XmlAttributeAttribute()> _
Public id As Integer

'<remarks/>
<System.Xml.Serialization.XmlIgnoreAttribute()> _
Public idSpecified As Boolean

'<remarks/>
<System.Xml.Serialization.XmlAttributeAttribute()> _
Public question As String

'<remarks/>
<System.Xml.Serialization.XmlAttributeAttribute()> _
Public response As Integer

'<remarks/>
<System.Xml.Serialization.XmlIgnoreAttribute()> _
Public responseSpecified As Boolean

'<remarks/>
<System.Xml.Serialization.XmlAttributeAttribute()> _
Public result As Integer

'<remarks/>
<System.Xml.Serialization.XmlIgnoreAttribute()> _
Public resultSpecified As Boolean
End Class
Public Shared Function addresponse(ByVal newResponse As Schema7Ihsurveyresponse) As String

Dim serializer As XmlSerializer
serializer = New XmlSerializer(GetType(Schema7Ihsurveyresponse))
Dim ms As MemoryStream
'Try
ms = New MemoryStream
serializer.Serialize(ms, newResponse)
'Catch ex As Exception
' ms.Close()
'Return (-1)
' End Try
ms.Close()
Dim xmlresponse As String = System.Text.Encoding.UTF7.GetString(ms.ToArray)
Dim cmd As New SqlClient.SqlCommand
cmd.CommandText = "insertResponseDetails"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlClient.SqlParameter("@.xml", xmlresponse))
Dim cn As New SqlClient.SqlConnection
cn.ConnectionString = Configuration.ModuleConfig.GetSettings.ConnectionString
cmd.Connection = cn
cn.Open()
Dim newResponseid As Integer
'Try
'newResponseid = CInt(cmd.ExecuteScalar)

' Catch ex As Exception
'Return -1

'End Try
Return xmlresponse
End Function
End Class

Saturday, March 24, 2012

Object reference not set to an instance of an object (user controls)

I have a user control WebsiteFooter.ascx. In the code-behind I have

public void Test()

{
...
}

//

Then in the parent page code-behind Website.aspx.cs I have the script

protected WebsiteFooter WebsiteFooter1;

and the following script in the Page_Render event:

WebsiteFooter WebsiteFooter1 = new WebsiteFooter();
this.WebsiteFooter1.Test();

When I run the program I get the message:
Object reference not set to an instance of an object.

I would appreciate suggestion to resolve this problem.

Thank you.That's not going to work.

I'm not sure what you're trying to do. However, if you just want to dynamically add the Footer User Control, you can use the following in your codebehind:

 UserControl DynamicUserControl;
DynamicUserControl = Page.LoadControl( "WebsiteFooter.ascx" );
FooterPlaceholder.Controls.Add( DynamicUserControl );

If Test() is called from your WebsiteFooter.ascx's own code (such as in its Page_Load method), then it will execute without you having to call it.

Does that help?
Thank you for your reply. I'm sorry that my question was not clear.

what I want to be able to do is call the function, or a control's (which exists in a user control) method from the parent page or from another user control.

e.g. i have a logon.ascx & a header.ascx - which has a label control with text 'Sign In'.
when the user logs on, I want to be able to change the text in header.ascx to 'Sign Off'.

Likewise, I would also like to be able to run a function from another user control.
e.g.
uc1 has function1() which runs a query
uc2 has function2() which also runs a query

I would like to make only one trip to the server and retrieve both sets of data and bind to controls within their respective user controls.

Thanks again for your interest.
Having your ASPX page work with your ASCX user control is explained in theQuickStart Tutorials:
Exposing User Control Properties

You could, for example, have a property in your ASCX called IsUserAuthenticated. If false, the label is "Sign In"; if true, the label is "Log Off". The property would be tested and the label set during the User Control's Page_Load method.

As to having one ASCX talk to another, that's a bad idea. ASCX user controls should be "encapsulated" ... that is, they should not rely on the existence of other ASCX controls. Instead, your ASPX page should handle any communication between ASCX user controls.
Hi -

>>
Instead, your ASPX page should handle any communication between ASCX user controls.
>
That is what I am attempting to do when I get the error message 'Object reference not set to an instance of an object'.

From the aspx page I am trying to run a function which is contained in the user control UCHeader.ascx.cs

In the aspx.cs page I have -

protected UCHeader myUCHeader
--
private void btnSubmit_Click(object sender, System.EventArgs e)
{
UCHeader myUCHeader = new UCHeader();
myUCHeader.FunctionWithinUCHeader(); <-- this line gives error
}

In UCHeader.ascx.cs I have a pulic function

public void FunctionWithinUCHeader()
{
....
}

Thanks.
If you tell me what FunctionWithinUCHeader will actually do, I'll write a sample for you.
public void GetTransactionList()
{
SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["connString"]);
//
myConnection.Open();
//
SqlCommand myCommand = new SqlCommand("sp_GetTransactionList", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
//
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = myCommand;
sda.Fill(ds);
dgList.DataSource = ds.Tables[0];
dgList.DataBind();
//
myCommand.Connection.Close();
}
You should allow your user control's own Page_Load method call this GetTransactionList() method.

public void Page_Load( object sender, EventArgs e )
{
GetTransactionList();
}

User Controls should be as self-sufficient as possible ... populating its own controls, and managing its own events (such as when the page posts back).