VB. NET Add multiple ChildNodes in a Treeview - asp.net

I have many records in a database and I need to populate my treeview dynamically like this: Below is just an example of what I need:
TreeView1.Nodes(a).ChildNodes.Add(New TreeNode("ChildNode " & b))
TreeView1.Nodes(a).ChildNodes(b).ChildNodes.Add(New TreeNode("ChildNode 2 lvl " & b))
I'm getting the records from a MySQL Db and I need to know how can I add multilevel ChildNodes into a loop For ... Next etc...
Do you have any suggestion or idea???

if you want to work with various levels of Treenodes you can use Find function
Dim TempNode As TreeNode = TreeView1.Nodes.Find("Node where I want to add SubNode", True).FirstOrDefault
TempNode.Nodes.Add("SubNode", "SubNode")
This way you can add SubNode to any Node you pick.
.Find("key",True)finds treenodes with following key and .FirstOrDefault picks first. Finally you just add new SubNode to Tempnode.
You considered you are getting it dynamically and from MySql. It may cause error like "Action beeing preformed on this control is being called from the wrong thread. Marshal to the correct thread using Contol.Invoke or Control.BeginInvoke to perform this action." Simply change TempNode.Nodes.Add("SubNode", "SubNode") to TreeView1.Invoke(Sub() TempNode.Nodes.Add("SubNode", "SubNode"))
EXAMPLE:
Dim comm As String = "SELECT * FROM YourTableName"
Dim SqlCmnd as SqlCommand = New SqlCommand(comm, YourMySqlConnection)
Dim READER As SqlDataReader
READER = SqlCmnd.ExecuteReader
While READER.Read
Dim NewNode As TreeNode = New TreeNode(READER.Item("origCategoryID"))
TreeView1.Nodes.Add(NewNode)
NewNode.Nodes.Add(READER.Item("categoryOrderID"))
End While
READER.Close()
EXAMPLE 2:
While READER.Read
If TreeView1.Nodes.Find(READER.Item("OrigCatOrderID"), True).Length > 0 Then
Dim NewNode As TreeNode = TreeView1.Nodes.Find(READER.Item("OrigCatOrderID"), True).FirstOrDefault
NewNode.Nodes.Add(READER.Item("CatOrderID"), READER.Item("CatOrderID"))
Else
TreeView1.Nodes.Add(READER.Item("OrigCatOrderID"), READER.Item("OrigCatOrderID"))
TreeView1.Nodes(READER.Item("OrigCatOrderID")).Nodes.Add(READER.Item("CatOrderID"), READER.Item("CatOrderID"))
End While

Related

Sorting a datatable

I have an asp.net listbox on my page, that I want to sort.
E.g: listbox(lstChooseFields)
MY VB code:
Private Sub LoadColumns()
If drpScreen.SelectedIndex > -1 Then
Dim daLookup As New LookupTableAdapters.LookupTableAdapter
Dim dtLookup As New System.Data.DataTable
dtLookup = daLookup.GetNestedControlValues("EM", "ExcelExport.aspx", "drpScreen", "drpScreen", drpScreen.SelectedValue)
lstChooseFields.DataSource = dtLookup
lstChooseFields.DataValueField = "LKP_ControlValue"
lstChooseFields.DataTextField = "LKP_ControlText"
lstChooseFields.DataBind()
'Dispose
daLookup.Dispose()
End If
End Sub
I have done some searching and found something like 'dtLookup.DefaultView.Sort = "LKP_ControlText" that I can use but it does not work. I don't want to sort in my database only on this page, this listbox (lstChooseFields).
So if you want to sort for the datatable then you have tried dtLookup.DefaultView.Sort = "LKP_ControlText" but you have missed out one piece of word there dtLookup.DefaultView.Sort = "LKP_ControlText asc". This generally works if LKP_ControlText is a column name in the datatable
You must use the word ascthere. which i couldnt find in your question.
After getting the dataTable sorted you can copy the same structure to another datatable if u want by using
Dim dtDuplicateLookup As New DataTable()
dtDuplicateLookup = dtLookup.DefaultView.ToTable(True)
and then access dtDuplicateLookup for further use if you want to retain the previous datatable as it is.
Use the .sorted property for the list box as shown here.
lstChooseFields.Sorted = True
UPDATE: your method was right but just tune it this way. I think you missed the DESC part. The second expression tells it how to sort the dataview.
Dim dataView As New DataView(table)
dataView.Sort = " column_name DESC" //DESC or ASC as per requirement
Dim dataTable AS DataTable = dataView.ToTable()
Else try this. After sorting a defaultview, generally you have to loopback through it
foreach(DataRowView r in table.DefaultView)
{
//... here you get the rows in sorted order
//insert the listbox items one by one here using listbox.add or listbox.insert commands
}

How do I program a TreeView in asp.net?

I have a tree view in my asp.net page, but I don't know how to program another childnodes. In my treeview I want to show data from my table "MyTable". My table is divided into id, name and level, but in the first node I want to show the first level, in the childnode I want to show the rows they are in second level and as another childnode I want to show the third level in "MyTable". I tried to do that with the following code:
Dim SqlCommand As String = String.Empty
Me.TreeView1.Nodes.Clear()
SqlString = "select name, id from MyTable"
Try
MsDb = New Clase_Coneccion
Dim Dr As OleDb.OleDbDataReader = MsDb.ConsultaDB(SqlString, MsDb.MsSqlServer)
While (Dr.Read())
Dim Nodo As New TreeNode
Nodo.Text = Dr("name").ToString()
Nodo.Value = Dr("id").ToString()
Nodo.PopulateOnDemand = (CInt(Dr("id")) > 0)
TreeView1.Nodes.Add(Nodo)
End While
Return
Catch ex As Exception
End Try
That's how I get the first nodes with all the names from "MyTable", but I don't know how to specify the childnodes for 2nd and 3d level. Any idea?

Iterating over SearchResultCollection is Very Slow

I'm running an LDAP query that returns multiple entries and stores them inside a SearchResultCollection. I'm iterating over the SearchResultCollection like so:
// results is my SearchResultCollection object
foreach (SearchResult sr in results)
{
... do things to each SearchResult in here ...
}
This seems like the most logical way to do this, but loop is incredibly slow. When I step through the loop with the debugger, I find that it's the very first step of initializing the foreach loop that takes the time - the actual iterations are instantaneous.
In addition, when I view the contents of the SearchResultCollection while debugging, the watch takes just as long to load the contents of the variable.
I have a theory that the SearchResultCollection doesn't actually contain complete SearchResult objects, but rather references to entries in the Active Directory server that are then individually fetched when I iterate over the SearchResultCollection object. Can anyone confirm this theory? And is there a better (faster) way to fetch a set of LDAP entries?
I suffered from the same problem and the methodology in the post below was much quicker then my own:
http://msdn.microsoft.com/en-us/library/ms180881(v=vs.80).aspx
... to answer you question yes it seems as if you try to process the entries directly while still in the loop by using something like:
If Not UserAccount.GetDirectoryEntry().Properties("sAMAccountName").Value Is Nothing Then sAMAccountName = UserAccount.Properties("sAMAccountName")(0).ToString()
... this has a drastic impact on performance, you can get around this by adding the collection to a Dictionary within the loop and then processing the dictionary:
Dim searchResult As SearchResult
Dim dictLatestLogonDatesTemp As New Dictionary(Of String, Date)
SearchResults1 = mySearcher.FindAll()
For Each searchResult In SearchResults1
Dim propertyKey,sAMAccountName As String
Dim dteLastLogonDate As Date = Nothing
For Each propertyKey In searchResult.Properties.PropertyNames
Dim valueCollection As ResultPropertyValueCollection = searchResult.Properties(propertyKey)
For Each propertyValue As Object In valueCollection
If LCase(propertyKey) = LCase("sAMAccountName") Then sAMAccountName = propertyValue
If LCase(propertyKey) = LCase("lastLogon") Then dteLastLogonDate = Date.FromFileTime(propertyValue)
Next propertyValue
Next propertyKey
If sAMAccountName <> Nothing Then dictLatestLogonDatesTemp.Add(sAMAccountName, dteLastLogonDate)
Next searchResult
It is a bit restrictive bacause a dictionary ony has two entries but you can comma seperate other values or use a dictionary of values in the dictionary:
Dim tempDictionary As Dictionary(Of String, Dictionary(Of String, String))
Hope this helps someone!
I would like to submit that adding them to a datatable also works very well and allows for more properties than a dictionary. I went from iterating 2000 users in the searchresultscollection taking almost 2 minutes to less that 1-2 seconds. Hope this helps others.
Private Sub getAllUsers()
Dim r As SearchResultCollection
Dim de As DirectoryEntry = New DirectoryEntry(GetCurrentDomainPath)
Dim ds As New DirectorySearcher(de)
ds.SearchScope = SearchScope.Subtree
ds.PropertiesToLoad.Add("name")
ds.PropertiesToLoad.Add("distinguishedName")
ds.PropertiesToLoad.Add("objectSID")
ds.Filter = "(&(objectCategory=person)(objectClass=user))" '(!userAccountControl:1.2.840.113556.1.4.803:=2) not disabled users
PleaseWait.Status("Loading Users...")
Application.DoEvents()
r = ds.FindAll()
Dim dt As New DataTable
dt.Columns.Add("Name")
dt.Columns.Add("SID")
For Each sr As SearchResult In r
Dim SID As New SecurityIdentifier(CType(sr.Properties("objectSID")(0), Byte()), 0)
dt.Rows.Add(sr.Properties("name")(0).ToString(), SID.ToString)
Next
With lstResults
lstResults.DataSource = dt
.DisplayMember = "name"
.ValueMember = "SID"
.Items.Sort()
End With
End Sub
There may be some ways to decrease the response time:
restrict the scope of the search
use a more restrictive search filter
use a base object closer to the object(s) being retrieved.
see also
LDAP: Mastering Search Filters
LDAP: Programming practices
LDAP: Search Best Practices

Reducing SQL connections to just 1 - ASP.net VB

I am currently working on an asp.net web page with a GridView displaying a table from a database. This GridView has 4 DropDownLists that will be used to filter the data shown on the GridView. When the page loads 4 Sub routines are run, each one connecting to the database with a select statement to fill the DropDownList with relevant filter headings.
Initially, I had one connection with a loop that populated all of the drop downs but these contained duplicates. I then split the filling of each DDL so that the select statements could contain DISTINCT.
I would like (and am sure there is a way here) to be able to populate all of the DDLs with data from one connection.
Code for one connection:
Protected Sub FillDepDDL()
Dim conn As New SqlConnection()
conn.ConnectionString = WebConfigurationManager.ConnectionStrings("TestDBConnectionString").ConnectionString
Dim connection As New SqlConnection(conn.ConnectionString)
connection.Open()
Const FillAllQS As String = "SELECT DISTINCT [Department] FROM [Employees]"
Dim command As New SqlCommand(FillAllQS, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim sel As New ListItem
sel.Text = "Please Select"
sel.Value = "*"
DDLDepartment.Items.Add(sel)
While reader.Read
Dim Deplist As New ListItem()
Deplist.Value = reader("Department")
Deplist.Text = reader("Department")
DDLDepartment.Items.Add(Deplist)
End While
reader.Close()
conn.Close()
End Sub
The other 3 column names: FirstName > DDLFN, LastName > DDLLN, Wage > DDLWag.
This is only a test DB and the princibles learned here will be applied to a larger live project.
I'm sure some guru will be able to work this out easily but I just can't get my head round it even after hours of searching.
Thanks in advance.
I'm adding this in as answer because I cannot format it in a comment, but this doesn't answer the original question of how to write the sql to return all three distinct result sets. Instead, it answers how to rewrite the code you have above so that connections are properly disposed of in case of an exception.
Protected Sub FillDepDDL()
Dim Deplist As ListItem
Dim sel As New ListItem
sel.Text = "Please Select"
sel.Value = "*"
DDLDepartment.Items.Add(sel)
Using conn As New SqlConnection(WebConfigurationManager.ConnecitonString("TestDBConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT DISTINCT [Department] FROM [Employees]", conn)
conn.Open()
Using reader = cmd.ExecuteReader()
While reader.Read
Deplist = New ListItem()
Deplist.Value = reader("Department")
Deplist.Text = reader("Department")
DDLDepartment.Items.Add(Deplist)
End While
End Using
End Using
End Using
End Sub
I don't see any reason for you to try to return all three results in a single query. That will just make your code unnecessarily complicated just to save a millisecond or two. Connection pooling handles the creation of connections on the database server for you, so opening a new connection in your code is very fast.

linq with Msaccess [duplicate]

I have a *.MDB database file, and I am wondering if it is possible or recommended to work against it using LINQ in C#. I am also wondering what some simple examples would look like.
I don't know a lot about LINQ, but my requirements for this task are pretty simple (I believe). The user will be passing me a file path to Microsoft Access MDB database and I would like to use LINQ to add rows to one of the tables within the database.
What you want is a LINQ to ODBC provider, or a LINQ to JET/OLEDB provider.
Out of the box, MS doesn't make one. There may be a 3rd party who does.
Actually I recently (today) discovered that you can access an Access database with LinqToSql. It must be in the 2002 or newer format, you will not be able to drag and drop the tables to your datacontext so either manually create the objects in your dbml or you can use SQL Server Migration for Access to move it to a sql server and then drag and drop all you want. When you want to actually create the context pass it an OleDbConnection. Use your standard Jet.OLEDB.4.0 connection string on the OleDbConnection and you are good to go. Not sure of the limitation this may incurr though. I just did a quick sample and did an OrderBy without issue.
I wrote a small sample program to test this out with David's answer. You'll need to make an access database and manually create the DBML for Linq-to-SQL, as you cannot drag 'n drop them.
Inserts fail, citing Missing semicolon (;) at end of SQL statement. but queries seem to work alright.
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using Linq2Access.Data;
namespace Linq2Access
{
class Program
{
static readonly string AppPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
static readonly string DbPath = Path.Combine(AppPath, "Data", "database.accdb");
static readonly string DbConnString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + DbPath + "';Persist Security Info=False;";
static void Main(string[] args)
{
if (!File.Exists(DbPath))
throw new Exception("Database file does not exist!");
using (OleDbConnection connection = new OleDbConnection(DbConnString))
using (DataRepositoryDataContext db = new DataRepositoryDataContext(connection))
{
List<dbProject> projects = new List<dbProject>();
for (int i = 1; i <= 10; i++)
{
dbProject p = new dbProject() { Title = "Project #" + i };
for (int j = 1; j <= 10; j++)
{
dbTask t = new dbTask() { Title = "Task #" + (i * j) };
p.dbTasks.Add(t);
}
projects.Add(p);
}
try
{
//This will fail to submit
db.dbProjects.InsertAllOnSubmit(projects);
db.SubmitChanges();
Console.WriteLine("Write succeeded! {0} projects, {1} tasks inserted",
projects.Count,
projects.Sum(x => x.dbTasks.Count));
}
catch(Exception ex)
{
Console.WriteLine("Write FAILED. Details:");
Console.WriteLine(ex);
Console.WriteLine();
}
try
{
//However, if you create the items manually in Access they seem to query fine
var projectsFromDb = db.dbProjects.Where(x => x.Title.Contains("#1"))
.OrderBy(x => x.ProjectID)
.ToList();
Console.WriteLine("Query succeeded! {0} Projects, {1} Tasks",
projectsFromDb.Count,
projectsFromDb.Sum(x => x.dbTasks.Count));
}
catch (Exception ex)
{
Console.WriteLine("Query FAILED. Details:");
Console.WriteLine(ex);
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
}
You can use a DataSet. There are linq extensions that will allow you to query the data with all that LINQ goodness we have become use to :)
eICATDataSet.ICSWSbuDataTable tbl = new eICATDataSet.ICSWSbuDataTable();
ICSWSbuTableAdapter ta = new ICSWSbuTableAdapter();
ta.Fill(tbl);
var res = tbl.Select(x => x.ProcedureDate.Year == 2010);
I have seen this question a lot and in several fora. I made a go at it and here is a complete answer for those who have been looking at it.
LinQ was not made for Access. However, many of the queries will work with Access, including delete procedure. So, according to me, there are only 2 crucial deficiencies when working with Access, which are:
not being able to save data.
not being able to drag and drop objects onto the dbml
Insert will fail with the error "missing semicolon (;)". This is because LinQ save procedure was made to save data and retrieve the primary key ID of the record saved in one go. We know that you cannot execute multiple SQL statements in Access, so that is the reason for that failure.
Update will fail with the error "record not found". An update procedure will of cause look for the record to be updated then update it. I cannot tell why it wouldn't find it, when normal LinQ query to find a record works fine.
Because there is so much benefit to use LinQ, I figured out how to work around the deficiency, while enjoy the other benefits throughout my application. This is how (NB: My codes are in VB.net, but you can convert if required):
Create the LinQ to SQL (.dbml) class to manage your LinQ against the access database, and a way to manager your save procedure. Below is the full procedures of what I created and I now work with LinQ to Access without any problems:
Add a DataGridView on a form. Add buttons for Add, Edit & Delete
Code to fill the grid:
Private Sub ResetForm()
Try
Using db As New AccessDataClassesDataContext(ACCCon)
Dim rows = (From row In db.AccountTypes
Where row.AccountTypeID > 1
Order By row.AccountTypeID Ascending
Select row).ToList()
Me.DataGridView1.DataSource = rows
End Using
Catch ex As Exception
MessageBox.Show("Error: " & vbCr & ex.ToString, "Data Error", MessageBoxButtons.OK)
End Try
End Sub
DetailForm
Code to set control values
Private Sub ResetForm()
Try
If _accountTypeID = 0 Then
Exit Sub
End If
Using db As New AccessDataClassesDataContext(ACCCon)
'Dim rows = (From row In db.AccountTypes
' Where row.AccountTypeID = _accountTypeID
' Order By row.AccountTypeID Ascending
' Select row.AccountTypeID, row.AccountType, row.LastUpdated).ToList()
Dim rows = (From row In db.AccountTypes
Where row.AccountTypeID = _accountTypeID
Select row).ToList()
For Each s In rows
Me.AccountTypeIDTextBox.Text = s.AccountTypeID
Me.myGuidTextBox.Text = s.myGuid
Me.AccountTypeTextBox.Text = s.AccountType
Me.AcHeadIDTextBox.Text = s.AcHeadID
Me.DescriptionTextBox.Text = s.Description
Me.LastUpdatedDateTimePicker.Value = s.LastUpdated
Next
End Using
Catch ex As Exception
End Try
End Sub
LinQToSQLClass
You will have to add the data objects to the dbml manually since you cannot drag and drop when using Access. Also note that you will have to set all the properties of the fields correctly in the properties windows. Several properties are not set when you add the fields.
Code to Save
Public Function SaveAccountType(Optional ByVal type As String =
"Close") As Boolean
Dim success As Boolean = False
Dim row As New AccountType
Using db As New AccessDataClassesDataContext(ACCCon)
If _accountTypeID > 0 Then
row = (From r In db.AccountTypes
Where r.AccountTypeID = _accountTypeID).ToList()(0)
If String.IsNullOrEmpty(row.AccountTypeID) Then
MessageBox.Show("Requested record not found", "Update Customer Error")
Return success
End If
End If
Try
With row
.myGuid = Me.myGuidTextBox.Text
.AccountType = Me.AccountTypeTextBox.Text
.Description = Me.DescriptionTextBox.Text
.AcHeadID = Me.AcHeadIDTextBox.Text
.LastUpdated = Date.Parse(Date.Now())
End With
If _accountTypeID = 0 Then db.AccountTypes.InsertOnSubmit(row)
db.SubmitChanges()
success = True
Catch ex As Exception
MessageBox.Show("Error saving to Customer: " & vbCr & ex.ToString, "Save Data Error")
End Try
End Using
Return success
End Function
Now replace these two lines:
If _accountTypeID = 0 Then db.AccountTypes.InsertOnSubmit(row)
db.SubmitChanges()
with something like this:
Dim cmd As IDbCommand
cmd = Me.Connection.CreateCommand()
cmd.Transaction = Me.Transaction
cmd.CommandText = query
If myGuid.Trim.Length < 36 Then myGuid = UCase(System.Guid.NewGuid.ToString())
cmd.Parameters.Add(New OleDbParameter("myGuid", row.myGuid))
cmd.Parameters.Add(New OleDbParameter("AccountType", row.AccountType))
cmd.Parameters.Add(New OleDbParameter("Description", row.Description))
cmd.Parameters.Add(New OleDbParameter("AcHeadID", row.AcHeadID))
cmd.Parameters.Add(New OleDbParameter("LastUpdated", Date.Now))
If AccountTypeID > 0 Then cmd.Parameters.Add(New OleDbParameter("AccountTypeID", row.AccountTypeID))
If Connection.State = ConnectionState.Closed Then Connection.Open()
result = cmd.ExecuteNonQuery()
cmd = Me.Connection.CreateCommand()
cmd.Transaction = Me.Transaction
cmd.CommandText = "SELECT ##IDENTITY"
result = Convert.ToInt32(cmd.ExecuteScalar())
The last part of the code above is what gets you the ID of the record saved. Personally, I usually make that an option, because I don't need it in most of the cases, so I don't need to add that overhead of fetching back data every time a record is saved, I am happy just to know a record was saved.
That is the overhead added to LinQ, which causes Insert to fail with Access. Is it really necessary to have it? I don't think so.
You may have noted that I normally put my Update and Insert procedures together, so that saves me time and has address both the Insert & Update procedures in one go.
Code for Delete:
Private Sub DelButton_Click(sender As Object, e As EventArgs) Handles DelButton.Click
Using db As New AccessDataClassesDataContext(ACCCon)
Dim AccountTypeID As Integer = Me.DataGridView1.CurrentRow.Cells(0).Value
Dim row = From r In db.AccountTypes Where r.AccountTypeID = AccountTypeID
For Each detail In row
db.AccountTypes.DeleteOnSubmit(detail)
Next
Try
db.SubmitChanges()
Catch ex As Exception
' Provide for exceptions.
MsgBox(ex)
End Try
End Using
End Sub
Now you can enjoy LinQ to Access! Happy coding :)
LINQ to SQL only works for SQL Server databases. What you need is the Microsoft Entity Framework. This makes object oriented access to your mdb. From this you can run LINQ queries.
http://msdn.microsoft.com/en-us/library/aa697427(vs.80).aspx

Resources