Value of type <DataTable> can not be converted to <database.table name> - asp.net

We are developing an ASP.Net web application with a SQL Server database and would like to populate an ASP.Net label control with the total number of students who are enrolled at the school whenever the home page is displayed.
We created the following strongly typed controls with the dataset designer:
DataTable: Students
DataSet: DataSetAllStudents
TableAdapter: StudentsTableAdapter
In the VB.Net code-behind file I used the following code to start the process of obtaining a total count of enrolled students.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim studentsAdapter As New DataSetAllStudentsTableAdapters.StudentsTableAdapter
Dim studentsTableRow As Knowledge_Academy.Students
studentsTableRow = studentsAdapter.GetData
End Sub
We get an error on this line of code:
studentsTableRow = studentsAdapter.GetData
This is the error:
Value of type 'Knowledge_Academy.DataSetAllStudents.StudentsDataTable' cannot be
converted to 'Knowledge_Academy.Students'.
GetData contains the query that will return the total number of enrolled students. We would also like to know how to get the value returned into this ASP.Net label control.
<asp:Label ID="LabelTotalNumberOfStudents" runat="server" Text="Label"></asp:Label>

First, ensure that you load the data only on the first load and not on every postback. Second, since GetData returns a DataTable with all rows you can use it's Rows.Count property:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim daStudents = New DataSetAllStudentsTableAdapters.StudentsTableAdapter()
Dim tblStudents = studentsAdapter.GetData()
LblStudentNumber.Text = String.Format("{0}", tblStudents.Rows.Count)
End If
End Sub
Of course it would be better to add a new query to the TableAdapter that returns a scalar value with the number of students. That would require much less resources.

Related

How to link DataSet to .aspx page in asp.net

I created a DataSet named CardInfo.xsd in Visual Studio 2015 that works perfectly
When I try to show data from it using a TableAdapter (which also works fine and displays the specific query I set up), I get an error in the code behind file.
It says CardInfo is not defined and also that the TableAdapter (CardInfoTableAdapters.TableTableAdapter) is not defined.
However it lets me select any other .xsd or .mdf files in the project, so I feel like the DataSet is not broadcasting itself to the rest of the project.
In the end it is supposed to get the value from the text box and show the row whose primary id matches the inputted number.
Here is the code to create the DataSet on the page:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
GetCardInfo(cardentry.Text)
End If
End Sub
Protected Sub GetCardInfo(ByVal Entry As String)
Dim myDataSet As New CardInfo
Dim cardDA As New CardInfoTableAdapters.TableTableAdapter
cardDA.Fill(myDataSet.Entry, Entry)
GridViewRetrieval.DataSource = myDataSet.Tables("Table")
GridViewRetrieval.DataBind()
End Sub

dex express controls how to get ID value from ComboBox

I have ID Number and name. I am using a datacontrol and this "Select Number, Name from My Table"
I can see both in the combobox, but if I pick one I can't get any data from it. what do I do?
I have used native .NET and get the ID value using this>
Protected Sub lstWorkList_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstWorkList.SelectedIndexChanged
Try
Session("gblWorkerNumber") = Me.lstWorkList.SelectedValue.ToString
but in dev express there is no "post back" and I can't get their example to work either.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If (Not IsCallback) Then
CmbCountry.Value = "Mexico" ' I want to get my Number into a session var
FillCityCombo("Mexico")
End If
End Sub
seems to me like their example just hardcodes "Mexico" in ??? how does that work anyway?
Their Example is on this page:
http://demos.devexpress.com/aspxeditorsdemos/ASPxComboBox/ClientAPI.aspx
this is what I was after, the .Value
Protected Sub cbxWorkerName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxWorkerName.SelectedIndexChanged
Session("WorkerNumber") = Me.cbxWorkerName.Value
' in native .NET it is either .selectedindex or .selectedValue one gives the name and the other gives the Number
End Sub

Removing item from a listbox that is binding to a database table

i. I have a form that allow users add multiple phone numbers using a listbox and two buttons to add to the listbox and to remove from the listbox if they make a mistake and want to correct it before saving to the phone number table in the database.
ii. I have another form which allows them to edit what has been saved, which means they can either remove or add more as the case maybe.
The first (i) works perfectly well while the second (ii) does not. What I discovered is that i can only remove what I added but not what is coming from the database table. How do I do that?
Below is my code sample for the second form (ii):
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Contact_Phone(getId)
End If
end sub
Private Sub Contact_Phone(ByVal FK_CID As Integer)
Dim strSQL As String
strSQL = "Select PK_PNID,PN_Number From tblPhoneNumber where FK_CID=" & FK_CID
With cClass
.BindListBox(Me.lbPhone, strSQL, "PN_Number", "PK_PNID")
End With
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
Me.lbPhone.Items.Remove(Me.lbPhone.SelectedItem.Text)
Catch ex As Exception
If ex.Message = "Object reference not set to an instance of an object." Then
Exit Sub
End If
Me.lblErr.ForeColor = Drawing.Color.Red
Me.lblErr.Text = ex.Message
End Try
End Sub
When in the form(ii) an user is deleting a phone number, just delete it from the db, so next time when the phone numbers are shown in the form(ii) the deleted phone number will not be there.
If you do not want to make a post back on delete button click(which will erase the user added phone numbers in the list box as it has not been saved to the db till now), then make an AJAX call to the sever passing the values and delete the number.

Web Controls Not Talking to Each other in ASP.NET using VB.NET

I have an asp.net page that loads two controls, Control A and Control B. Control A has some generic form submit and clear buttons that trigger click events in its' own code behind which use reflection to call the update function in Control B which has a few input fields. I have debugged this and everything seems to be in order, however; when the update function in control B is called the input fields are not returning a value when using inputname.text or me.inputname.text. Does anyone have any ideas why this is not working? Any guidance would be appreciated.
This is the code in Control A's codebehind which calls the update method in Control B's code behind
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Try
Dim lctlControl = Session("SelectedQstnCtl")
Dim methodObj = lctlControl.GetType().GetMethod("UpdateGenInfo", BindingFlags.NonPublic Or BindingFlags.Instance)
' Execute UpdateGenInfo method to update the data
methodObj.Invoke(lctlControl, Nothing)
Catch ex As Exception
'TODO: check for concurrency error here
End Try
End Sub
This is the update function in Control B that is being called. The session values are being passed, but the form fields are not.
Protected Sub UpdateGenInfo()
Dim lclUtil As New clUtility
Dim genInfo As New clGenInfo
Try
Dim dt As Integer
'Update Data for 1-2
dt = genInfo.UpdateGenInfo_E1_01_02(Session("ConnStrEP"), Me.varLastUpdate, Session("AppNo"), Session("RevNo"), _
Me.txtPrName.Text, Me.txtPrAddr1.Text, Me.txtPrAddr2.Text, _
Me.txtPrCity.Text, Me.txtPrState.Text, Me.txtPrZip.Text)
Catch ex As Exception
'Display error
lclUtil.DisplayMsg(Me.lblErrMsg, String.Format("Error Location: Sub LoadGenInfo (ctlE1_01_02) {0}", ex.Message))
End Try
End Sub
The most likely cause is that the control instance stored in the session is not the control instance on the current page. For example, if you're storing the control instance in the session when the page is first loaded, and retrieving it on post-back, it will be a different instance.
If you can't give Control A a direct reference to Control B, then change your code to store the reference in the Page.Items collection:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Page.Items("SelectedQstnCtl") = TheSelectedQstnCtl
End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Dim lctlControl = DirectCast(Page.Items("SelectedQstnCtl"), YourControlClass)
lctlControl.UpdateGenInfo()
End Sub
I see you are using reflection which might be an overkill for that task.Try referencing the method in the control directly.Make then method UpdateGenInfo public and then reference it like this.
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
Try
Dim lctlControl = CType(Session("SelectedQstnCtl"),YourControlClass)
lctlControl.UpdateGenInfo()
Catch ex As Exception
End Sub
Public Function UpdateGenInfo()
'your code here
Catch ex As Exception
End Try
End Function
This way you can easily trace where your values are getting lost.Let me know how it goes.
Try yet another simple approach working demo here
In control a
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim testb1 = CType(Me.NamingContainer.FindControl("testb1"), testb)
testb1.UpdateGenInfo()
End Sub
In control b
Public Function UpdateGenInfo()
Try
Dim a = Me.TextBox1.Text
Catch ex As Exception
End Try
End Function
Aspx Parent Page
<uc1:testa ID="testa1" runat="server" />
<uc2:testb ID="testb1" runat="server" />
The controls in testb are in an update panel.Try this and let me know if this works.

VB.NET Checkboxes checking

I have a form which contains a checkbox field. On page load I want to create a separate checkbox for each customer in my Database. The code I have to create the checkboxes for each customer works fine. However, I also want to check in the database if the customer is set to unauthorized if they are then I want to check there box. I also have code for the case where the user checks a box. If a box is checked I update the database setting the unauthorized attribute to true. My problem is when I check a box it works fine and the box is checked, however if I reload the page all the boxes are unchecked. So either my database update is not updating the database or the way I check on page load for checked boxes is incorrect. Any ideas?
The code for the asp checkbox field:
<asp:CheckBoxList id="check1" AutoPostBack="True" TextAlign="Right" OnSelectedIndexChanged="Check" runat="server">
</asp:CheckBoxList>
The Code for the page load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sql As String = "SELECT Name, unauthorized, ID FROM Customer ORDER BY Name"
Dim dt As DataTable = db.execDataTableQuery(sql, "Customer")
Dim i As Integer
For i = 0 To dt.Rows.Count - 1
check1.Items.Add(New ListItem(CStr(dt.Rows(i).Item("Name"))))
check1.Items(i).Value = CInt(dt.Rows(i).Item("ID"))
check1.Items(i).Text = CStr(dt.Rows(i).Item("Name"))
If CInt(dt.Rows(i).Item("unauthorized")) = 1 Then
check1.Items(i).Selected = 1
Else
check1.Items(i).Selected = 0
End If
Next
End Sub
The code to update the database:
Sub Check(ByVal sender As Object, ByVal e As EventArgs)
Dim sql As String
If check1.SelectedItem.Selected = 1 Then
sql = "UPDATE Customer SET unauthorized = 1 WHERE ID = #ID"
db.execUpdateQuery(sql, New SqlClient.SqlParameter("#ID", check1.SelectedItem.Value))
Else
sql = "UPDATE Customer SET unauthorized = 0 WHERE ID = #ID"
db.execUpdateQuery(sql, New SqlClient.SqlParameter("#ID", check1.SelectedItem.Value))
End If
End Sub
End Class
You need to wrap you code in Page_Load in a Not Page.IsPostback, otherwise on postback no events are triggered and the selection is lost since you're overwriting it from database.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostback Then
' databind your CheckBoxList '
End If
End Sub

Resources