Currently, I'm using an AJAX Handler to populate the JSTree:
$(function () {
$("#jstree").jstree({
"json_data": {
"ajax": {
"url": "AJAXHandler.aspx?action=GetMenu"
}
},
"plugins": ["themes", "json_data", "dnd"]
})
.bind("move_node.jstree", function (node, ref, position, is_copy, is_prepared, skip_check) {
console.log(node); });
});
The handler actually makes a database call, loops through the menu items, creates a JSON object that is serialized, sent back, and rendered:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Select Case Request("action")
Case "GetMenu"
GetMasterMenu()
Case "UpdateMenuHiearchy"
UpdateMenuHiearchy()
End Select
End Sub
Private Sub GetMasterMenu()
Dim dt As DataTable = GetMenu()
Dim nodesList As New List(Of JsTreeNode)()
PopulateNodes(dt, nodesList)
Dim ser As New JavaScriptSerializer()
Dim res As String = ser.Serialize(nodesList)
Response.ContentType = "application/json"
Response.Write(res)
Response.[End]()
End Sub
Private Sub PopulateNodes(ByRef dt As DataTable, ByVal nodes As List(Of JsTreeNode))
Dim parents() As DataRow = dt.Select("PARENT_MENU_ID = 0")
'Root Nodes
For Each dr As DataRow In parents
Dim node As New JsTreeNode()
node.attributes = New Attributes()
node.attributes.id = dr("APPLICATION_MENU_ID").ToString
node.attributes.rel = "root" & dr("APPLICATION_MENU_ID").ToString
node.data = New Data()
node.data.title = dr("DESCRIPTION")
node.state = "open"
'Check for Children
Dim strSQL As New StringBuilder
With strSQL
.Append(" SELECT * FROM APPLICATION_MENU WHERE PARENT_MENU_ID = " & dr("APPLICATION_MENU_ID") & "")
End With
Dim dtChildren As DataTable = DatabaseManager.Query(strSQL.ToString)
If dtChildren.Rows.Count > 0 And dtChildren IsNot Nothing Then
For Each drChild As DataRow In dtChildren.Rows
AddChildNodes(dt, dr("APPLICATION_MENU_ID"), node)
Next
End If
node.attributes.mdata = "{draggable : true}"
nodes.Add(node)
Next
End Sub
Private Sub AddChildNodes(ByRef dt As DataTable, ByVal parentID As Integer, ByVal node As JsTreeNode)
Dim strSQL As New StringBuilder
With strSQL
.Append(" SELECT * FROM APPLICATION_MENU WHERE PARENT_MENU_ID = " & parentID.ToString & "")
End With
Dim dtChildren As DataTable = DatabaseManager.Query(strSQL.ToString)
node.children = New List(Of JsTreeNode)()
For Each drChild As DataRow In dtChildren.Rows
Dim cnode As New JsTreeNode()
cnode.attributes = New Attributes()
cnode.attributes.id = drChild("APPLICATION_MENU_ID").ToString
node.attributes.rel = "folder"
cnode.data = New Data()
cnode.data.title = drChild("DESCRIPTION")
cnode.attributes.mdata = "{draggable : true }"
strSQL = New StringBuilder
With strSQL
.Append(" SELECT * FROM APPLICATION_MENU WHERE PARENT_MENU_ID = " & drChild("APPLICATION_MENU_ID") & "")
End With
Dim dtChildren2 As DataTable = DatabaseManager.Query(strSQL.ToString)
If dtChildren.Rows.Count > 0 And dtChildren IsNot Nothing Then
AddChildNodes(dt, drChild("APPLICATION_MENU_ID"), cnode)
End If
node.children.Add(cnode)
Next
End Sub
The idea here is to bind the move_node to a function that will hit the handler and update the database as to where I moved the object. I've been able to create the bind to do that. The problem, however, is that I can't seem to obtain the ID. I'm setting it in the attributes in the population of the JSON object, but when I do a watch on the NODE and REF objects via console.log, the id field is empty.
What gives? Any ideas? Am I missing something vital?
After fiddling with it once again, I found the answer:
cnode.attributes
node.attributes
It must be name specific underneath, these must be cnode.attr and node.attr to work.
You are indeed correct-
JSTree V1+ uses the jquery bindings,etc.. Therefore you need to use the attr to obtain the objects attributes - also on a side note, IE7- are case sensitive with the node data, eg:
$("#node").attr("id")!=$("#node").attr("ID")
Related
I'm trying to increment my variable on a button click. It increments only once. It seems as though it's getting lost when it reloads the page.
I'm using the following code:
Dim ItemSelect As New ArrayList()
Dim Quantities As New ArrayList()
Dim itemQtyOrdered As Integer
Public Sub ShtickDataList_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles ShtickDataList.ItemCommand
If e.CommandName = "ViewCart" Then
Response.Redirect("~/ShoppingCart.aspx")
End If
If e.CommandName = "addToCart" Then
Dim itemQuantity As DropDownList = e.Item.FindControl("QuantityDropDown")
itemQtyOrdered = itemQuantity.SelectedValue
ItemSelect.Add(e.CommandArgument)
Quantities.Add(itemQtyOrdered)
Session("itemInCart") = ItemSelect
Session("quantities") = Quantities
viewInvoice()
End If
End Sub
Protected Sub viewInvoice()
Dim itemSelected As ArrayList = DirectCast(Session("itemInCart"), ArrayList)
Dim QuantityofItem As ArrayList = DirectCast(Session("quantities"), ArrayList)
Dim conn As SqlConnection
Dim comm As SqlCommand
Dim reader As SqlDataReader
Dim purimConnection2 As String = ConfigurationManager.ConnectionStrings("Purim").ConnectionString
conn = New SqlConnection(purimConnection2)
comm = New SqlCommand("SELECT ProductName FROM Products WHERE ProductID = #ProductID", conn)
Dim i As Integer
For i = 0 To ItemSelect.Count - 1
comm.Parameters.Add("#ProductID", Data.SqlDbType.Int)
comm.Parameters("#ProductID").Value = ItemSelect(i)
Next
Try
conn.Open()
reader = comm.ExecuteReader()
ViewCartlink.Text = "View Cart: (" & ItemSelect.Count & ")"
Finally
conn.Close()
End Try
End Sub
Ah, you may be referring to ItemSelect and Quantities lists. You need to look for them in Session and only create them if they are not in the Session. I am rusty on VB.NET, so this is C# version. In Page_Load:
ItemSelect = (ArrayList)Session["itemInCart"];
if (ItemSelect == null)
{
ItemSelect = new ArrayList();
Session["itemInCart"] = ItemSelect;
}
and the same for Quantities.
Also, your loop in viewInvoice method is wrong. For more than one item in ItemSelect list you are adding multiple parameters with the same name. You probably only wanted to do it once with
comm.Parameters("#ProductID").Value = ItemSelect(ItemSelect.Count - 1)
I have a user control that uses an UpdatePanel. The controls is essentially a table with a Button. When the user clicks the Button, a modal popup opens that allows them to select some value. Data for the table (which uses a Repeater as its DataSource) is stored in a session variable between partial postbacks (when the UpdatePanel fires) as a list of objects. Everything works fine if I have just one control but if I use this control in the same page more than once, the list of objects in the session variables get combined and are not separated for each control. I thought this might be because the session variable names are not unique, so anywhere I call or use the variable, I do it like this:
Dim sessionName as string = Me.UniqueID & "_" & "userNotificationDS"
Session(sessionName) = myListOfObjects
But this has not changed the outcome. Anyone know what I might be doing wrong here? If you believe the full code would be helpful, let me know.
Control Server Code:
Protected Sub delete_click(ByVal sender As Object, ByVal e As EventArgs)
Dim btn As LinkButton = CType(sender, LinkButton)
Dim ds As New List(Of myObject)
sessionName = Me.UniqueID & "_" & "myDataSet"
ds = Session(sessionName.ToString)
Dim id As String = btn.CommandArgument
ds.RemoveAll(Function(userNotification) userNotification.User.NetworkID.Equals(id))
Session(sessionName.ToString) = ds
bindData(ds)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
sessionName = Me.UniqueID & "_" & "myDataSet"
If (Session(sessionName.ToString) IsNot Nothing) Then
bindData(Session(sessionName.ToString))
End If
End Sub
Private Function buildPagedSet(ByVal userNotification As List(Of myObject)) As PagedDataSource
Dim ps As PagedDataSource = New PagedDataSource()
ps.DataSource = userNotification
ps.AllowPaging = True
ps.PageSize = numRows
Return ps
End Function
Public Sub bindData(ByVal commentList As List(Of myObject))
sessionName = Me.UniqueID & "_" & "myDataSet"
Dim currentPage As Integer = 0
Dim ps As PagedDataSource
Dim numLable As Label
Dim denomLable As Label
Dim curPage As Integer = 1
Dim totalPage As Integer = 0
If (Not myObject Is Nothing) Then
Try
ps = buildPagedSet(commentList)
totalPage = ps.PageCount
Session(sessionName.ToString) = commentList
rowTotal = ps.Count
'for paging
If Not (ViewState(Me.UniqueID & "_Page") Is Nothing) Then
currentPage = Convert.ToInt32(ViewState(Me.UniqueID & "_Page"))
Else
ViewState(Me.UniqueID & "_Page") = 1
currentPage = 1
End If
If (currentPage > 0 And currentPage <= ps.PageCount) Then
ps.CurrentPageIndex = currentPage - 1
Me.dataRepeateUsers.DataSource = ps
Me.dataRepeateUsers.DataBind()
ElseIf (currentPage >= ps.PageCount) Then
ViewState(Me.UniqueID & "_Page") = Convert.ToInt32(ViewState(Me.UniqueID & "_Page")) - 1
ElseIf (currentPage <= 0) Then
ViewState(Me.UniqueID & "_Page") = Convert.ToInt32(ViewState(Me.UniqueID & "_Page")) + 1
Else
End If
Catch ex As Exception
Throw
End Try
Else
Dim emptySet As New List(Of myObject)
Me.dataRepeateUsers.DataSource = emptySet
Me.dataRepeateUsers.DataBind()
End If
End Sub
The control is instantiated like this:
Me.notifier1.bindData(notificationList)
In this example, when the user deletes something from notifier1 ( the delete_click event) the object is removed from the list and it gets added back to the session. If anything causes notifier2's update panel to fire, it will display the same exact data as notifier1
My hunch is your are storing your myListOfObjects in the session but reusing that object somwhere and modifying it and storing it in the Session again with a different key. It is probably still the same object being stored for both Session keys.
You can do a simple test by storing an object in the Session with two differnt keys. Then pull it out using the first key and modify that object and don't reassign it back to the Session (not needed anyways). Now pull the other object out from the second key and look at it. It will match the modifications because the object is the same object just stored under two diffeent keys in the Session.
If Kelsey's hunch is correct, you could store each of the instances of myListOfObjects in a Dictionary(Of String, myListOfObjectsType) and use the .UniqueID as the key (the Of String part).
I am having problems with Creating Control Arrays and getting the Column Names for a table, I know that my string works as I have used the outputted string straight as a SQL query, the problem lies where it seems not to find any of the rows in the table(that i know are their, using the If lrd.HasRows Then I have seen that it does not find any rows (lrd.HasRows = False). Is their a diffent Connection string for INFORMATION_SCHEMA.COLUMNS ?
'Finds the Column Name
Public Sub findSQLColumnName(ByRef i As Integer, ByRef OutputValue As String, ByVal tableName As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim lrd As SqlDataReader
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Output
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
Call FindConnectionString(con) ' finds connection string
cmd.Parameters.Add(TableNameParm)
cmd.Parameters.Add(LocationParm)
Call SQLSELECT_WHERE("INFORMATION_SCHEMA.COLUMNS", "COLUMN_NAME AS Output, ORDINAL_POSITION", True, " (TABLE_NAME = #Tablename) AND (ORDINAL_POSITION = #Location)", con, cmd, lrd)
Try
' While lrd.Read() ' code writen within here for what is to be done with selected data.
'Call findSQLColumnValue("Output", lrd, OutputValue)
'End While
If lrd.HasRows Then
lrd.Read()
Call findSQLColumnValue("Output", lrd, OutputValue)
lrd.Close()
'Close connection before Redirecting.
Else
lrd.Close()
End If
' Catch ex As Exception
Finally
con.Close()
End Try
End Sub
'Finds the value of a Column
Public Sub findSQLColumnValue(ByRef ColumnName As String, loader As SqlDataReader, ByRef OutputValue As String)
OutputValue = (Convert.ToString(loader(ColumnName))).Trim
End Sub
'Button Click (Creates the control array)
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim SQLCode As New SQLCode
Dim TableLength As Integer
Dim lblText(100) As String
Call SQLCode.SQLFindNoColumns("PatientClinicalinformation", TableLength, lblTitlePatient, lblText)
For i As Int16 = 1 To TableLength
' Create the label control and set its text attribute
Dim Label2 As New Label
Call SQLCode.findSQLColumnName(i.ToString, lblText(i), "PatientClinicalinformation")
Label2.Text = lblText(i)
Dim Literal2 As New Literal
Literal2.Text = "<br />"
' Add the control to the placeholder
PlaceHolder1.Controls.Add(Label2)
Label2.ID = "lbl" & i
PlaceHolder1.Controls.Add(Literal2)
Next
End Sub
'SelectWhere
Public Sub SQLSELECT_WHERE(ByVal Tables As String, ByVal Columns As String, ByVal WHERE As Boolean, ByVal WHEREStatement As String, ByRef connection As SqlConnection, ByRef command As SqlCommand, ByRef loader As SqlDataReader)
connection.Open()
command.Connection = connection
If WHERE = False Then
command.CommandText = " SELECT " & Columns & " FROM " & Tables
End If
If WHERE = True Then
command.CommandText = " SELECT " & Columns & " FROM " & Tables & " WHERE " & WHEREStatement
End If
command.CommandText = command.CommandText
loader = command.ExecuteReader()
End Sub
I found the solution! the code all worked there was a problem with the array TableNameParm
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Output
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
The TableNameParm.Direction should be an input but is set to a Output
Dim TableNameParm As New SqlParameter("Tablename", tableName) 'adds in the new paramenter UserName
TableNameParm.Direction = ParameterDirection.Input
Dim LocationParm As New SqlParameter("Location", i) 'adds in the new paramenter UserName
LocationParm.Direction = ParameterDirection.Input
It's hard to say without knowing the function SQLSELECT_WHERE, but it's possible one or more of the parameters is not correct. Try skipping that function and use
cmd = New SqlCommand("SELECT ... WHERE", conn)
You can also test the number of rows by using count(*) in the query.
I am trying to delete a row from a gridview (based on a condition) and then add than row to another gridview inside of the "master" gridview's RowDataBound event. Originally I did not know that in order to call .DeleteRow(i) you needed to have an "ondelete" event handler. However, since all the gridview's .DeleteRow method does is call this event handler, I am confused as to how to use it. Can someone please help point me in the right direction?
Protected Sub grdProduct_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdProduct.RowDataBound
' Grey out expired products
Dim row As GridViewRow
row = e.Row
Dim incomingDate As String
Dim incomingStatus As String = ""
incomingDate = row.Cells(3).Text.ToString()
incomingStatus = row.Cells(5).Text.ToString()
If (e.Row.RowType <> DataControlRowType.DataRow) Then
Exit Sub
End If
Try
Dim expDate As Date = incomingDate
If (expDate < DateTime.Today Or incomingStatus.Equals("D")) Then
'Create object for RowValues
Dim RowValues As Object() = {"", "", "", "", "", ""}
'Create counter to prevent out of bounds exception
Dim i As Integer = row.Cells.Count
'Fill row values appropriately
For index As Integer = 0 To i - 1
RowValues(index) = row.Cells(index).Text
Next
'create new data row
dProdRow = dProdtable.Rows.Add(RowValues)
dProdtable.AcceptChanges()
grdProduct.DeleteRow(e.Row.RowIndex)
End If
Catch ex As Exception
End Try
End Sub
Protected Sub grdProduct_Delete(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles grdProduct.RowDeleting
'Not sure what to do here
End Sub
The best way to do this is to manipulate this at the datasource level rather than manipulating the UI components themselves.
For example:
if(!IsPostback)
{
DataTable one = ...
DataTable two = ...
var removeRows = (from c in one.AsEnumerable()
where c.Field<DateTime>("incomingDate")< incomingDate ||
c.Field<string>("incomingStatus")=="D"
select c).ToList();
for(var item in removeRows)
{
two.ImportRow(item);
}
//now delete from initial table
foreach(var item in removeRows)
{
one.Rows.Remove(item);
}
//Now bind both grids
grid1.DataSource=one;
grid1.DataBind();
grid2.DataSource=two;
grid2.DataBind();
}
Update - Sample toy program in VB.NET Hopefully you can adapt it to your situation.
Sub Main
Dim one As New DataTable()
one.Columns.Add("one", GetType(Integer))
For i As Integer = 0 To 9
Dim r As DataRow = one.NewRow()
r.ItemArray = New Object() {i}
one.Rows.Add(r)
Next
Dim two As New DataTable()
two.Columns.Add("one", GetType(Integer))
For i As Integer = 0 To 9
Dim r As DataRow = two.NewRow()
r.ItemArray = New Object() {i}
two.Rows.Add(r)
Next
Dim removeRows = (From c In one.AsEnumerable() Where c.Field(Of Integer)("one") = 5).ToList()
For Each item As DataRow In removeRows
two.ImportRow(item)
Next
For Each item As DataRow In removeRows
one.Rows.Remove(item)
Next
End Sub
I just realized that you are using VB.NET. You should be able to translate the above from C# to VB.NET. The general idea is there, anyway.
As you can see from the commented out code, I'm trying to get the model dropdown be affected by + selCurrentManuf.Text.
I get this error
'selCurrentManuf' is not declared. It may be inaccessible due to its protection level.
How can this be solved?
I can access the drop down in another part of the page like this..
Dim sc1_currentmanuf As String = CType(e.Item.FindControl("selCurrentManuf"), DropDownList).Text
However in the function i am trying to use selCurrentManuf does not have access to e
Dim sc1_currentmanuf As String = CType(dlContacts.Items(0).FindControl("selCurrentManuf"), DropDownList).Text
Dim myQuery As String = "SELECT * FROM c5_model where c5_manufid = " + sc1_currentmanuf
Right click on your .aspx page, and select the command Convert To Web Application.
Then you'll be able to write:
Dim myQuery As String =
String.Format("SELECT * FROM c5_model WHERE c5_manuf = '{0}'",
selCurrentManuf.SelectedItem.Text )
I'm assuming your functions are inside a class in your App_Code or another dll and not on the code behind of the page.
If so do this instead:
I'm assuming you have something like this on your asp page code behind:
Protected Sub selCurrentManuf_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
GetCurrentModel(selCurrentManuf.Text)
End Sub
Change Your GetCurrentModel Code To:
Function GetCurrentModel(Byval c5_manuf as String) As DataSet
Dim mySession = System.Web.HttpContext.Current.Session
Dim myQuery As String = "SELECT * FROM c5_model " 'where c5_manuf = " + + c5_manuf
Dim myConnection As New MySqlConnection(mySession("localConn"))
myConnection.Open()
Dim myCommand As New MySqlCommand(myQuery, myConnection)
Dim myDataAdapter = New MySqlDataAdapter(myCommand)
Dim myDataset As New DataSet
myDataAdapter.Fill(myDataset, "c5_model")
Dim dr As DataRow = myDataset.Tables(0).NewRow
myDataset.Tables(0).Rows.Add(dr)
GetCurrentModel = myDataset
myConnection.Close()
End Function