Dynamically create datatable that allows population multiple times - asp.net

I'm trying to dynamically create a datatable that will allow me to populate single records multiple times when a procedure is executed. I know how to create the datatable with the columns I need but my problem is that every time I execute the sub routine to add a record it re-initializes the datatable and wipes out the previously populated record. How do I create the datatable so that it initializes only once? I've tried initializing during the Page_Load event with a 'Not IsPostback' condition but that doesn't work. Any other ideas?
Partial Public Class ContactLookup
Inherits System.Web.UI.Page
Dim dtContacts As New DataTable
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
dtContacts = New DataTable
dtContacts.Columns.Add("Email", GetType(String))
dtContacts.Columns.Add("AccountNum", GetType(String))
End If
End Sub
Protected Sub btnAddContact_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAddContact.Click
Dim AcctNum As String = txtLocAcct.Text
Dim Email As String = txtEmail.Text
Dim drContacts As DataRow = dtContacts.NewRow
drContacts("Email") = Email
drContacts("AccountNum") = AcctNum
dtContacts.Rows.Add(drContacts)
End Sub
End Class

If I am correct than you need the table returned by the query as datatable. If its so then you can try this. Change your SqlCommand like this,
var dt =new DataTable(); // a new table to populate dynamically.
var reader = cmd.ExecuterReader(CommandBehaviour.SequentialAccess");
dt.Load(reader);
return dt; // now your dt will be query dependent.
Sorry the answer is in C#. You can convert it to VB at http://converter.telerik.com
Updated Answer
In your case i would suggest create a class instead of datatables and datacolumns. See a sample below:
public class Student
{
public string Name{get;set;}
public int Roll{get;set;}
}
In your code behind
private Student _stud = new Student();
private void FillObjects(){
_stud.Name= txtName.Text;
_stud.Roll=Convert.ToInt32(txtRoll.Text);
}
private void ButtonClick{
FillObjects();
YourClass.SaveMethod(_stud);
}

Related

vb.net CefSharp.Windows document.getElementById

We used webbrowser control to login website in VB.NET, now we are going to us CefSharp.
We have made a simple test form. Clicking on the button sets the "toegangscode". It works, but when I go to next field wachtwoord (password) and type 1 first character the "toegangscode" field will be made empty. What I am doing wrong ?
Public Class Form1
Public WithEvents browser As ChromiumWebBrowser
Public Sub New()
' This call is required by the designer.
InitializeComponent()
Dim settings As New CefSharp.WinForms.CefSettings()
CefSharp.Cef.Initialize(settings)
browser = New CefSharp.WinForms.ChromiumWebBrowser("https://diensten.kvk.nl/inloggen.html") With {
.Dock = DockStyle.Fill}
Panel1.Controls.Add(browser)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim jsScript1 = <js><![CDATA[document.getElementById("username").focus();]]></js>.Value
browser.ExecuteScriptAsync(jsScript1)
Dim jsScript2 As String = <js><![CDATA[document.getElementById("username").value = "xxxxxx";]]></js>.Value
browser.ExecuteScriptAsync(jsScript2)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim bCanExecuteJavascriptInMainFrame As Boolean = browser.CanExecuteJavascriptInMainFrame
Dim bIsBrowserInitialized As Boolean = browser.IsBrowserInitialized
If bIsBrowserInitialized Then
browser.ShowDevTools()
End If
End Sub
End Class

Cannot refer to an instance member of a class from a shared method

How you get a public shared function outside of a Protected Sub, use the values from within a protected sub to postBack to the same webpage. The postback reply works, but the query of the function fails at (Line 44 Char 17 "fqdom = dom & ".forest.local")
Imports System
Imports System.IO
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.DirectoryServices.ActiveDirectory
Partial Class _Default
Inherits System.Web.UI.Page
Dim dom As String
Dim Group1 As String
Dim Group2 As String
Dim usrname As String
Dim fqdom As String
Dim netdom As String
Private Function GetDataFromArrayList() As ArrayList
Dim DomainList As New ArrayList()
DomainList.Add(New ListItem("d1", "dom1"))
DomainList.Add(New ListItem("d2", "dom2"))
Return DomainList
End Function
Protected Sub Selection_Changed(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
For Each item As ListItem In GetDataFromArrayList()
DropDownList1.Items.Add(item)
Next
End If
End Sub
Public Shared Function GetGroups() As ArrayList
Dim groupList As New ArrayList()
Dim usrname As String
Dim fqdom As String
'Dim netdom As String
Dim groupCheck As String
fqdom = dom & ".forest.local"
Dim entry As System.DirectoryServices.DirectoryEntry
Dim searcher As System.DirectoryServices.DirectorySearcher
Dim result As System.DirectoryServices.SearchResult
Try
entry = New System.DirectoryServices.DirectoryEntry("LDAP://" & fqdom)
searcher = New DirectorySearcher()
searcher.SearchRoot = entry
searcher.Filter = "(samAccountName=" & usrname & ")"
searcher.PropertiesToLoad.Add("memberOf")
result = searcher.FindOne()
Dim groupCount As Integer = result.Properties("memberOf").Count
For groupCounter As Integer = 0 To groupCount - 1
groupCheck = CStr(result.Properties("memberOf")(groupCounter))
groupCheck = groupCheck.Remove(groupCheck.LastIndexOf(",CN="))
groupCheck = groupCheck.Replace("CN=", "")
groupList.Add(groupCheck)
Next groupCounter
Catch ex As Exception
End Try
Return groupList
End Function
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If IsPostBack Then
Dim name As Boolean = False
If Not TextBox1.Text = String.Empty Then
name = True
End If
If name = False Then
StatusLabel.Text = "Update Status: Please Enter Name"
ElseIf name = True Then
Group1 = "groupb1"
Group2 = "groupb2"
Try
form1.Visible = False
Dim groups As New ArrayList()
groups = GetGroups()
Dim group As String
For Each group In groups
'NameLabel.Text = group
If (group.Contains(Group1)) Then
Group1.Text = "User: " & usrname & " is in group1"
End If
If (group.Contains(Group2)) Then
Group1.Text = "User: " & usrname & " is in group2"
End If
Next
fqdn.Text = "Domain: " & dom & ".forest.local"
NameLabel.Text = "User: " & usrname
Catch ex As Exception
End Try
Else
StatusLabel.Text = "Upload status: Error Please Retry later"
End If
End If
End Sub
End Class
Remove the Shared keyword from the method, so replace
Public Shared Function GetGroups() As ArrayList
with
Public Function GetGroups() As ArrayList
You cannot use instance variables like dom from within a Shared method.
You could also make those fields Shared. But that's not a good idea in ASP.NET since it could cause locks and concurrency issues and every request shared the same values(even of different users).
It's also not necessary since you want to use that method from a page method(button-click), so you need an instance of the page anyway.
If you need to persist a value across postback you can use a different way like using ViewState, Session or a HiddenField.

asp.net server control not saving state properly

I am trying to create an ASP.net server control that uses controls from the AjaxControlToolkit. Essentially, the control is a dropdownlist and a button. When the user clicks the button, a modal dialog (modalPopupExtender) opens. The dialog has a checkboxlist with a list of options to chose from. When the user selects their choice(s) and hits the Ok button, in the dialog, the dialog closes and the selected choices should get added to the dropdownlist. What is happening, though, is that when the user makes their selection and hits OK only the last item in the Checkboxlist gets added. I think it may have something to do with the inherited functions I override. Can anyone tell me what I may be doing wrong? Here is the relevant code:
<DefaultProperty("Text"), ToolboxData("<{0}:myServerControl runat=server>
</{0}:myServerControl >")> _
Public Class myServerControl
Inherits CompositeControl
Implements INamingContainer, IPostBackEventHandler
Private myDropDownListAs New DropDownList
Private addPlant As New Button
Private _updatePanel As UpdatePanel
Private _modalExtenderOne As AjaxControlToolkit.ModalPopupExtender
Private lblWarning As Label
Private cb1 As New CheckBoxList
Private btnSavePlants As New Button
Private btnCancel As New Button
Protected Overrides Function SaveViewState() As Object
Return New Pair(MyBase.SaveViewState(), Nothing)
End Function
Protected Overrides Sub LoadViewState(ByVal savedState As Object)
MyBase.LoadViewState(CType(savedState, Pair).First)
EnsureChildControls()
End Sub
Protected Overrides Sub CreateChildControls()
createDynamicControls()
MyBase.CreateChildControls()
End Sub
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
MyBase.OnInit(e)
End Sub
Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)
MyBase.OnLoad(e)
End Sub
Private Sub createDynamicControls()
Controls.Clear()
AddHandler btnSavePlants.Click, AddressOf saveItems_Click
_updatePanel = New UpdatePanel
Dim myTable As New Table
myTable = buildControl() ' a funciton that returns a built table
Dim myPanel As New Panel
myPanel = buildDialog() 'a function taht returns a build modal dialog
_updatePanel.ContentTemplateContainer.Controls.Add(myTable)
_updatePanel.ContentTemplateContainer.Controls.Add(myPanel)
Me.Controls.Add(_updatePanel)
End Sub
Protected Sub saveItems_Click(ByVal sender As Object, ByVal e As EventArgs)
Me.myDropDownList.Items.Clear()
Try
For Each i As ListItem In Me.cb1.Items
If (i.Selected = True) Then
Dim newLi As New ListItem
With newLi
.Selected = False
.Text = i.Text
.Value = i.Value
End With
Me.myDropDownList.Items.Add(newLi)
Else
End If
Next
Catch ex As Exception
End Try
End Sub
Public Sub bindSelections(ByVal myList As List(Of myObject))
For Each p As myObjectIn myList
Dim newLI As New ListItem
newLI.Value = p.EquipmentPK
newLI.Text = p.EquipmentID
Me.cb1.Items.Add(newLI)
Next
End Sub
Public Sub RaisePostBackEvent(ByVal eventArgument As String) Implements System.Web.UI.IPostBackEventHandler.RaisePostBackEvent
End Sub
End Class

Getting an ASP.NET error System.NullReferenceException: Object reference not set to an instance of an object?

I am completely new to ASP.NET and VB as well as C#. I am trying to add customers to a contact list out of a DB. Then the list can be referenced to call them up.
But when I try to run it I get System.NullReferenceException: Object reference not set to an instance of an object. In line 19.
Here is my code:
Page 1 is default page...it connects to the database and grabs the contact information and allows me to select the current contact and add them to a listbox on a separate page:
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Private SelectedCustomer As Customer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
If Not IsPostBack Then
ddlCustomers.DataBind()
End If
SelectedCustomer = Me.GetSelectedCustomer
Me.DisplayCustomer()
End Sub
Private Function GetSelectedCustomer() As Customer
Dim dvTable As dataview = CType(AccessDataSource1.Select( _
DataSourceSelectArguments.Empty), dataview)
dvTable.RowFilter = "CustomerID = " & ddlCustomers.SelectedValue
Dim drvRow As DataRowView = dvTable(0)
Dim customer As New Customer
customer.CustomerID = CInt(drvRow("CustomerID"))
customer.Name = drvRow("Name").ToString
customer.Address = drvRow("Address").ToString
customer.City = drvRow("City").ToString
customer.State = drvRow("State").ToString
customer.ZipCode = drvRow("ZipCode").ToString
customer.Phone = drvRow("Phone").ToString
customer.Email = drvRow("Email").ToString
Return customer
End Function
Private Sub DisplayCustomer()
lblAddress.Text = SelectedCustomer.Address
lblCityStateZip.Text = SelectedCustomer.City & ", " _
& SelectedCustomer.State & " " _
& SelectedCustomer.ZipCode
lblPhone.Text = SelectedCustomer.Phone
lblEmail.Text = SelectedCustomer.Email
End Sub
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
If Page.IsValid Then
Dim customerItem As New Customer
customerItem.Name = SelectedCustomer.ToString
Me.AddToCustomer(customerItem)
Response.Redirect("CustomerList.aspx")
End If
End Sub
Private Sub AddToCustomer(ByVal customerItem As Customer)
Dim customer As SortedList = Me.GetCustomer
Dim customerID As String = SelectedCustomer.CustomerID
If customer.ContainsKey(customerID) Then
customerItem = CType(customer(customerID), Customer)
Else
customer.Add(customerID, customerItem)
End If
End Sub
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Customer"), SortedList)
End Function
End Class
The next bit of code allows me to add the contact to a list box:
Partial Class Default2
Inherits System.Web.UI.Page
Private Customer As SortedList
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Customer = Me.GetCustomer
If Not IsPostBack Then Me.DisplayCustomer()
End Sub
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Cart"), SortedList)
End Function
Private Sub DisplayCustomer()
lstCustomer.Items.Clear()
Dim customerItem As Customer
For Each customerEntry As DictionaryEntry In Customer
customerItem = CType(customerEntry.Value, Customer)
lstCustomer.Items.Add(customerItem.Name)
Next
End Sub
Protected Sub lstCustomer_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstCustomer.SelectedIndexChanged
End Sub
End Class
The error occurs on line 19 (For Each customerEntry As DictionaryEntry In Customer) in the second set of code from the default2 class. Any ideas? I am completely new to ASP.NET just trying to learn. I more at home on PHP, Java, and Actionscript unfortunately.
I think the problem is in this function
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Cart"), SortedList)
End Function
You initialise Customer here but then pull out of Session("Cart")
I think what you meant to do is
Private Function GetCustomer() As SortedList
If Session("Customer") Is Nothing Then
Session.Add("Customer", New SortedList)
End If
Return CType(Session("Customer"), SortedList)
End Function
Now customer should always be initialised whereas before it might not have been which would cause the NullReferenceException that you are getting.

binding datatable to grid view

I have the following code:
Imports System.Data
Partial Class Students_AddWishes Inherits System.Web.UI.Page
Public dt As New DataTable
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dt.Columns.Add("ID", System.Type.GetType("System.Int32"))
dt.Columns.Add("univirsity", System.Type.GetType("System.Int32"))
dt.Columns.Add("major", System.Type.GetType("System.Int32"))
End Sub
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
Dim row1 As DataRow = dt.NewRow()
row1("ID") = dt.Rows.Count + 1
row1("univirsity") = ddlUnivs.SelectedValue
row1("major") = ddlMajors.SelectedValue
dt.Rows.Add(row1)
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
End Class
The problem is it shows only one row or record. How to make it shows many records?
Your page load event you are not checking if it is a post back:
If Not IsPostBack Then
'process code if it is not a post back
End If
Everytime you click the btnAdd button your page does a post back to the server.
I just noticed that you probably are not understanding the life time of an object.
You had done this in your code:
Public dt As New DataTable
The problem with that is you have defined this is a class variable and once the page has loaded you have an instance of type dt that may have some columns associated with it. But as soon as you record an event such as a button click that reference is destroyed and a new dt is created.
You will have to make some use of session variables or a database to store the state of dt.
Here is an example in C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", System.Type.GetType("System.Int32"));
dt.Columns.Add("univirsity", System.Type.GetType("System.Int32"));
dt.Columns.Add("major", System.Type.GetType("System.Int32"));
Session["MyDataTable"] = dt;
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable t = (DataTable)Session["MyDataTable"];
DataRow row1 = t.NewRow();
row1["ID"] = t.Rows.Count + 1;
row1["univirsity"] = 3;
row1["major"] = 31;
t.Rows.Add(row1);
Session["MyDataTable"] = t;
GridView1.DataSource = t;
GridView1.DataBind();
}
And the same code in vb.net:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not Page.IsPostBack Then
Dim dt As New DataTable()
dt.Columns.Add("ID", System.Type.[GetType]("System.Int32"))
dt.Columns.Add("univirsity", System.Type.[GetType]("System.Int32"))
dt.Columns.Add("major", System.Type.[GetType]("System.Int32"))
Session("MyDataTable") = dt
End If
End Sub
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim t As DataTable = DirectCast(Session("MyDataTable"), DataTable)
Dim row1 As DataRow = t.NewRow()
row1("ID") = t.Rows.Count + 1
row1("univirsity") = 3
row1("major") = 31
t.Rows.Add(row1)
Session("MyDataTable") = t
GridView1.DataSource = t
GridView1.DataBind()
End Sub
So now what the code does is instantiate a new datatable object as long as we are on the page (first post back) and adds the columns. Once it has defined the data table we throw it in some session state. When you click the add button you cannot in your previous code just keep using dt because dt scope was lost in your prior code. We do this by assigning the sessioned datatable which was stored prior to a temp datatable. We add the row and reset the session that way the next time we add a row it will display the second row, then third row, and so on...
I recommend a good asp.net book on such as Beginning ASP.net 3.5 in C# 2008. There are a ton of vb.net books on the same subject matter.
You need to save the datatable to Session, because local variables are not preserved. So you need to do:
protected override OnLoad(..) //or OnInit
{
dt = Session["DataTable"] as DataTable;
if (dt == null)
{
dt = new DataTable();
//load columns
}
}
protected override OnUnLoad(..)
{
Session["DataTable"] = dt;
}
Session saves the data table reference across postbacks as the web is stateless.

Resources