When I try my code to update the GridViewBox to update to my database I get the following error message
Object Reference not set to an instance of an Object
But I cannot quite figure it out. Would appreciate any Help I can get.
Imports MySql.Data.MySqlClient
Public Class Form1
//GLOBAL DELARATION
Dim conString As String = "Server=xxx;" & "Database=xxx;" & "Uid=xxx;" & "xxx;"
Dim con As New MySqlConnection(conString)
Dim cmd As MySqlCommand
Dim adapter As MySqlDataAdapter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
//TODO: This line of code loads data into the 'OlejnaDataSet.people' table. You can move, or remove it, as needed.
Me.PeopleTableAdapter.Fill(Me.OlejnaDataSet.people)
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub hent()
Me.PeopleTableAdapter.Fill(Me.OlejnaDataSet.people)
End Sub
Private Sub cleartxt()
TextBox_name.Text = ""
TextBox_position.Text = ""
TextBox_team.Text = ""
End Sub
Private Sub Add()
Dim sql As String = "INSERT INTO people(Name,Position,Team) VALUES(#NAME,#POSITION,#TEAM)"
cmd = New MySqlCommand(sql, con)
//PARAMETERS
cmd.Parameters.AddWithValue("#NAME", TextBox_name.Text)
cmd.Parameters.AddWithValue("#POSITION", TextBox_position.Text)
cmd.Parameters.AddWithValue("#TEAM", TextBox_team.Text)
//Open Connection and INSERT
Try
con.Open()
If cmd.ExecuteNonQuery() > 0 Then
MsgBox("Added")
cleartxt()
End If
con.Close()
hent()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
//UPDATE DATABASE
Private Sub UpdateDG(id As String)
Dim sql As String = "UPDATE people SET name='" + TextBox_name.Text + "', position='" + TextBox_position.Text + "', team='" + TextBox_team.Text + "' WHERE ID='" + id + "'"
//Open CON, EXECUTE UPDATE, CLOSE
Try
con.Open()
adapter.UpdateCommand = con.CreateCommand()
adapter.UpdateCommand.CommandText = sql
If adapter.UpdateCommand.ExecuteNonQuery() > 0 Then
MsgBox("You have now updated")
cleartxt()
End If
con.Close()
//REFRESH
hent()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Private Sub ButtonAdd_Click(sender As Object, e As EventArgs) Handles ButtonAdd.Click
Add()
End Sub
Private Sub ButtonDelete_Click(sender As Object, e As EventArgs) Handles ButtonDelete.Click
End Sub
Private Sub ButtonUpdate_Click(sender As Object, e As EventArgs) Handles ButtonUpdate.Click
Dim id As String = DataGridView1.SelectedRows(0).Cells(0).Value
UpdateDG(id)
End Sub
Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick
Dim name As String = DataGridView1.SelectedRows(0).Cells(1).Value
Dim position As String = DataGridView1.SelectedRows(0).Cells(2).Value
Dim team As String = DataGridView1.SelectedRows(0).Cells(3).Value
TextBox_name.Text = name
TextBox_position.Text = position
TextBox_team.Text = team
End Sub
End Class
Hope you have clicked Update button without select any rows in your DataGrid
Change your Update Button Click Event as follows:
Private Sub ButtonUpdate_Click(sender As Object, e As EventArgs) Handles ButtonUpdate.Click
If DataGridView1.SelectedRows.Count > 0 Then
Dim id As String = DataGridView1.SelectedRows(0).Cells(0).Value
UpdateDG(id)
End If
End Sub
Update
Please Declare and Intialize your Sql Adapter
Use as below:
SqlDataAdapter adapter = new SqlDataAdapter();
//UPDATE DATABASE
Private Sub UpdateDG(id As String)
Dim sql As String = "UPDATE people SET name='" + TextBox_name.Text + "', position='" + TextBox_position.Text + "', team='" + TextBox_team.Text + "' WHERE ID='" + id + "'"
//Open CON, EXECUTE UPDATE, CLOSE
Try
SqlDataAdapter adapter = new SqlDataAdapter();
con.Open()
adapter.UpdateCommand = con.CreateCommand()
adapter.UpdateCommand.CommandText = sql
If adapter.UpdateCommand.ExecuteNonQuery() > 0 Then
MsgBox("You have now updated")
cleartxt()
End If
con.Close()
//REFRESH
hent()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Related
Imports MySql.Data.MySqlClient
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim mstream As New System.IO.MemoryStream()
picture_me.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim arrImage() As Byte = mstream.GetBuffer()
mstream.Close()
Try
cmd = New MySqlCommand("insert into piccs(Photo,id) values(#image_data,#image_id")
cmd.Parameters.AddWithValue("#image_data", Nothing)
cmd.Parameters.AddWithValue("#image_id", arrImage)
cmd.ExecuteNonQuery()
MsgBox("saved")
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conn()
End Sub
Private Sub browser_image_Click(sender As Object, e As EventArgs) Handles browser_image.Click
Me.find_image.FileName = Nothing
If find_image.ShowDialog() = DialogResult.OK Then
' Dim query1 As String
' cmd = New MySqlCommand
'cmd.Connection = connect
'query1 = "Insert into picss(id, Photo) values('" & TextBox1.Text & "','" & find_image.SafeFileNames(x) & "',#IMAGE,'" & Batch & "')"
If Not Me.find_image.FileName = Nothing Then
Me.picture_me.ImageLocation = find_image.FileName
End If
End If
End Sub
End Class
This is my code for read data from EXCEL file using ODBC driver and write in MySql Database.
Public Class WebForm3
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MySqlCmd = New SqlCommand()
' Dim dialog As New System.Windows.Forms.OpenFileDialog()
'Dim dialog As New OpenFileDialog()
'dialog.Filter = "Excel files |*.xls;*.xlsx"
'dialog.InitialDirectory = "C:\"
'dialog.Title = "Select file for import"
'If dialog.ShowDialog() = DialogResult.OK Then
Try
Dim dt As DataTable
Dim buff0 As String
Dim buff1 As String
Dim buff2 As String
dt = ImportExceltoDatatable("C:\\Book1.xls")
For i = 0 To dt.Rows.Count - 1
buff0 = dt.Rows(i)(0)
buff1 = dt.Rows(i)(1)
buff2 = dt.Rows(i)(2)
Dim connStr As String = "server=localhost;user=root;database=ajaxsamples;port=3306;password=innoera;"
Dim connMysql As MySqlConnection = New MySqlConnection(connStr)
Dim sql As String = "INSERT INTO ajaxsamples.customers VALUES('" & buff0 & "','" & buff1 & "','" & buff2 & "')"
Dim cmd As MySqlCommand = New MySqlCommand(sql, connMysql)
cmd.ExecuteNonQuery()
cmd.Dispose()
connMysql.Close()
Next
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
End Try
'End If
End Sub
Public Shared Function ImportExceltoDatatable(filepath As String) As DataTable
' string sqlquery= "Select * From [SheetName$] Where YourCondition";
Dim dt As New DataTable
Try
Dim ds As New DataSet()
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filepath & ";Extended Properties=""Excel 12.0;HDR=YES;"""
Dim con As New OleDbConnection(constring & "")
con.Open()
Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim sqlquery As String = String.Format("SELECT * FROM [{0}]", myTableName)
'Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
'Dim sqlquery As String = String.Format("SELECT * FROM Sheet1$") ' "Select * From " & myTableName
Dim da As New OleDbDataAdapter(sqlquery, con)
da.Fill(ds)
dt = ds.Tables(0)
Return dt
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
Return dt
End Try
End Function
End Class
I got this error,
"Connection must be valid and open "
whats wrong in code? I am newbie for VB. Any help would be appreciated.
You forgot to open your connection.
Try
connMysql = New MySqlConnection
connMysql.ConnectionString = connStr
connMysql.Open() 'You forgot to open your connection
sql = "SELECT * FROM users"
cmd = New MySqlCommand(sql, connMysql)
cmd.ExecuteNonQuery()
cmd.Dispose()
Catch ex As Exception
'your error code here
Finally
connMysql.Close() 'close your connection
End Try
I have a form in which data gets insert. There are some checkboxlist. CheckboxList binds with table in db. Now after selecting items it should enter selected values in db table but it inserts empty strings.
I have two checkboxlist (products, payment) Payment works fine. problem is in products.
VB code
Private Sub list_business_hospital_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.PopulateProducts()
Me.PopulatePayments()
End Sub
Private Sub PopulateProducts()
productsList.Items.Clear()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from chemistsProducts"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("productName").ToString()
item.Value = sdr("productName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
productsList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
productsList.Items.Insert(0, New ListItem("All", "All"))
End Sub
Private Sub PopulatePayments()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from payment"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("paymentName").ToString()
item.Value = sdr("paymentID").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
ListPayment.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
ListPayment.Items.Insert(0, New ListItem("All", "All"))
End Sub
Private Sub save_Click(sender As Object, e As EventArgs) Handles save.Click
Dim selectedProducts As String = String.Empty
For Each chk As ListItem In productsList.Items
If chk.Selected = True Then
selectedProducts &= "<li>" + chk.Text + "</li>"
End If
Next
Dim payments As String = String.Empty
For Each chk As ListItem In ListPayment.Items
If chk.Selected = True Then
payments &= "<li>" + chk.Text + "</li>"
End If
Next
Try
Dim str1 As String = "INSERT INTO chemists (`products`, `payment`) values ('" + selectedProducts + "', '" + payments + "')"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
con.Open()
str2 = command.ExecuteReader
con.Close()
Response.Redirect("business-added.aspx")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Here Payment gets inserted what I have selected. Problem is in selectedProducts
Try below in page load,
If Not IsPostBack Then
Me.PopulateProducts()
Me.PopulatePayments()
End If
I'm almost done with a trial program where I add, edit and delete stuff from my MySQL database.
But I can't seem to make the delete button to work.
Here's my code for the Delete Button:
If IDNo = Nothing Then
MsgBox("Please choose an item to delete.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Successfully deleted an item.", MsgBoxStyle.Information)
Me.LoadPeople()
End If
The ERROR
http://stivigan.us.to/images/delete_error.jpg
And here's the rest of my Main Form.
Imports MySql.Data.MySqlClient
Public Class frm_main
Public sConnection As New MySqlConnection
Public IDNo As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
End If
LoadPeople()
End Sub
Public Sub LoadPeople()
Dim sqlQuery As String = "SELECT * FROM tbl_adbms_test"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim TABLE As New DataTable
Dim i As Integer
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(TABLE)
End With
list_view_people.Items.Clear()
For i = 0 To TABLE.Rows.Count - 1
With list_view_people
.Items.Add(TABLE.Rows(i)("IDNo"))
With .Items(.Items.Count - 1).SubItems
.Add(TABLE.Rows(i)("LastName"))
.Add(TABLE.Rows(i)("FirstName"))
End With
End With
Next
End Sub
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_add.Click
frm_add.ShowDialog()
End Sub
Private Sub btn_modify_Click(sender As Object, e As EventArgs) Handles btn_modify.Click
If IDNo = Nothing Then
MsgBox("Please choose a record to modify.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "SELECT LastName, FirstName FROM tbl_adbms_test WHERE IDNo='" & list_view_people.SelectedItems(0).Text & "'"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTable As New DataTable
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTable)
End With
frm_modify.IDNo = list_view_people.SelectedItems(0).Text
frm_modify.LastName = sqlTable.Rows(0)("LastName")
frm_modify.FirstName = sqlTable.Rows(0)("FirstName")
frm_modify.ShowDialog()
End If
End Sub
Private Sub list_view_people_MouseClick(sender As Object, e As MouseEventArgs) Handles list_view_people.MouseClick
IDNo = list_view_people.SelectedItems(0).Text
End Sub
Private Sub btn_delete_Click(sender As Object, e As EventArgs) Handles btn_delete.Click
If IDNo = Nothing Then
MsgBox("Please choose an item to delete.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Successfully deleted an item.", MsgBoxStyle.Information)
Me.LoadPeople()
End If
End Sub
End Class
Add Form
Public Class frm_add
Public sConnection As New MySqlConnection
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
End If
End Sub
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_save.Click
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
sConnection.Open()
End If
Dim sqlQuery As String = "INSERT INTO tbl_adbms_test(IDNo,LastName,FirstName) VALUES(NULL,'" & txt_last_name.Text & "','" & txt_first_name.Text & "')"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("The data was saved.", MsgBoxStyle.Information)
Dispose()
Close()
frm_main.LoadPeople()
End Sub
End Class
Edit Form
Imports MySql.Data.MySqlClient
Public Class frm_modify
Friend IDNo As Integer
Friend LastName As String
Friend FirstName As String
Public sConnection As New MySqlConnection
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
txt_last_name.Text = LastName
txt_first_name.Text = FirstName
End Sub
Private Sub btn_update_Click(sender As Object, e As EventArgs) Handles btn_update.Click
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
sConnection.Open()
End If
Dim sqlQuery As String = "UPDATE tbl_adbms_test SET LastName='" & txt_last_name.Text & "', FirstName='" & txt_first_name.Text & "' WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Record updated successfully.", MsgBoxStyle.Information)
Dispose()
Close()
frm_main.LoadPeople()
End Sub
End Class
Thanks in advance. :)
You don't have the connection open before executing the Delete command.
This is a common scenario when you keep a global connection object around in your code.
You gain nothing and there are always situations in which you end with the connection in a wrong state
You could write
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo=#id"
if sConnection.ConnectionState = ConnectionState.Closed Then
sConnection.Open
End If
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.Parameters.AddWithValue("#id", IDNo)
.ExecuteNonQuery()
End With
but I really suggest to remove your usage of the global connection object and replace it with a local MySqlConnection that will be created just when you use it and closed/destroyed after the usage. This is the intended usage of the Using Statement
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo=#id"
Using con = new MySqlConnection(connstring)
Using cmd = new MySqlCommand(sqlQuery, con)
con.Open
With cmd
.Parameters.AddWithValue("#id", IDNo)
.ExecuteNonQuery()
End With
End Using
End Using
Notice also that I have removed the string concatenation in your sqlQuery and used a safer parameterized approach (albeit in this scenario and if the ListView is not editable there are no real risk of sql injection)
Here is the Code:
VB:
Imports System.Web.Script.Serialization
Partial Class MyLanding
Inherits System.Web.UI.Page
Private LoginClass As New LoginClass
Private _dockStateCleared As Boolean = False
Private _conn As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Private ReadOnly Property CurrentDockStates() As List(Of DockState)
Get
'Get saved state string from the database - set it to dockState variable for example
Dim dockStatesFromDB As String = ""
_conn.Open()
Dim command As New SqlCommand("SELECT JavascriptStr FROM SysProperties WHERE (UserID = #UserID)", _conn)
command.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
Try
dockStatesFromDB = command.ExecuteScalar().ToString()
_conn.Close()
Catch ex As Exception
_conn.Close()
Me.CreateSavedLayout("")
End Try
Dim _currentDockStates As New List(Of DockState)()
Dim stringStates As String() = dockStatesFromDB.Split("|"c)
For Each stringState As String In stringStates
If stringState.Trim() <> String.Empty Then
_currentDockStates.Add(DockState.Deserialize(stringState))
End If
Next
Return _currentDockStates
End Get
End Property
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
If Not Page.IsPostBack Then
If CurrentDockStates.Count = 0 Then
Me.LoadItems()
End If
End If
End Sub
Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Init
Dim i As Integer = 0
While i < CurrentDockStates.Count
If CurrentDockStates(i).Closed = False Then
Dim dock As RadDock = CreateRadDockFromState(CurrentDockStates(i))
dlColumnOne.Controls.Add(dock)
CreateSaveStateTrigger(dock)
LoadUserControl(dock)
End If
System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
End While
End Sub
Protected Sub dlColumnOne_LoadDockLayout(ByVal sender As Object, ByVal e As DockLayoutEventArgs)
For Each state As DockState In CurrentDockStates
e.Positions(state.UniqueName) = state.DockZoneID
e.Indices(state.UniqueName) = state.Index
Next
End Sub
Protected Sub dlColumnOne_SaveDockLayout(ByVal sender As Object, ByVal e As DockLayoutEventArgs)
Dim stateList As List(Of DockState) = dlColumnOne.GetRegisteredDocksState()
Dim serializedList As New StringBuilder()
Dim i As Integer = 0
While i < stateList.Count
serializedList.Append(stateList(i).ToString())
serializedList.Append("|")
System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
End While
Dim dockState As String = serializedList.ToString()
If dockState.Trim() <> [String].Empty Then
_conn.Open()
Dim command As New SqlCommand([String].Format("update sysproperties set javascriptstr = '{0}' Where UserID = #UserID ", dockState), _conn)
command.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
command.ExecuteNonQuery()
_conn.Close()
End If
End Sub
Private Function CreateRadDockFromState(ByVal state As DockState) As RadDock
Dim dock As New RadDock()
dock.DockMode = DockMode.Docked
dock.UniqueName = state.UniqueName
dock.ID = String.Format("RadDock{0}", dock.UniqueName)
dock.ApplyState(state)
dock.Commands.Add(New DockCloseCommand())
dock.Commands.Add(New DockExpandCollapseCommand())
Return dock
End Function
Private Function CreateRadDock(ByVal DockTitle As String) As RadDock
Dim docksCount As Integer = CurrentDockStates.Count
Dim dock As New RadDock
dock.DockMode = DockMode.Docked
Dim UniqueName As String = Guid.NewGuid().ToString()
UniqueName = UniqueName.Replace("-", "")
dock.UniqueName = UniqueName
dock.ID = String.Format("RadDock{0}", UniqueName)
dock.Title = DockTitle
dock.Width = Unit.Pixel(400)
dock.Commands.Add(New DockCloseCommand())
dock.Commands.Add(New DockExpandCollapseCommand())
Return dock
End Function
Private Sub LoadItems()
Dim DocksDataTable As DataTable = Me.ReturnReports()
For i = 0 To DocksDataTable.Rows.Count() - 1
Dim dock As RadDock = Me.CreateRadDock(DocksDataTable.Rows(i).Item("ReportTitle").ToString())
Dim dz As RadDockZone = Me.dzColumnOne
Dim dl As RadDockLayout = Me.dlColumnOne
dz.Controls.Add(dock)
Me.CreateSaveStateTrigger(dock)
dock.Tag = DocksDataTable.Rows(i).Item("ReportPath")
Me.LoadUserControl(dock)
Next
End Sub
Public Function ReturnReports() As DataTable
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Dim Query As String = "SELECT Reports.ReportPath, Reports.ReportTitle, UserReports.UserID FROM UserReports INNER JOIN Reports ON UserReports.ReportID = Reports.ReportID WHERE (UserReports.UserID = #UserID)"
Dim adapter As New SqlDataAdapter
adapter.SelectCommand = New SqlCommand(Query, connection)
adapter.SelectCommand.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
Dim table1 As New DataTable
connection.Open()
Try
adapter.Fill(table1)
Finally
connection.Close()
End Try
Return table1
End Function
Private Function ReturnLayout() As DataTable
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Dim Query As String = "select * from sysproperties"
Dim adapter As New SqlDataAdapter
adapter.SelectCommand = New SqlCommand(Query, connection)
adapter.SelectCommand.Parameters.Add("#UserPropertiesID", SqlDbType.Int).Value = 1
Dim table1 As New DataTable
connection.Open()
Try
adapter.Fill(table1)
Finally
connection.Close()
End Try
Return table1
End Function
Private Sub LoadUserControl(ByVal dock As RadDock)
If String.IsNullOrEmpty(dock.Tag) Then
Return
End If
Dim usercontrol As Control = LoadControl(dock.Tag)
dock.ContentContainer.Controls.Add(usercontrol)
End Sub
Private Sub CreateSaveStateTrigger(ByVal dock As RadDock)
dock.AutoPostBack = True
dock.CommandsAutoPostBack = True
Dim saveStateTrigger As New AsyncPostBackTrigger()
saveStateTrigger.ControlID = dock.ID
saveStateTrigger.EventName = "DockPositionChanged"
UpdatePanel1.Triggers.Add(saveStateTrigger)
saveStateTrigger = New AsyncPostBackTrigger()
saveStateTrigger.ControlID = dock.ID
saveStateTrigger.EventName = "Command"
UpdatePanel1.Triggers.Add(saveStateTrigger)
End Sub
Private Sub CreateSavedLayout(ByVal JavascriptStr As String)
Dim sqlConn As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Dim strSqlInsert As String = "INSERT INTO SysProperties(UserID, JavascriptStr) VALUES (#UserID, #JavascriptStr)"
strSqlInsert += "; SELECT SCOPE_IDENTITY() ;"
Dim sqlCmd As New SqlCommand(strSqlInsert, sqlConn)
With sqlCmd.Parameters
.Add("#JavascriptStr", SqlDbType.Text).Value = JavascriptStr
.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
End With
sqlCmd.Connection.Open()
sqlCmd.ExecuteScalar()
sqlCmd.Connection.Close()
End Sub
Protected Sub btnAddReports_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddReports.Click
Try
Response.Redirect("~/MyUserAccount/SelectedReports.aspx", False)
Catch ex As Exception
End Try
End Sub
End Class
Your could looks fine. Possible reasons for this problem include the following:
Dragging the Dock control very quickly causes an ajax conflict, and an error is shown. To avoid this from happening you could show an AjaxLoading panel during the process of an ajax request (search/ask in the telerik forums for a sample showing how to do this). Additionally you should make sure the UpdatePanels on your site are configured as in the following online demo: http://demos.telerik.com/aspnet-ajax/dock/examples/myportal/defaultcs.aspx.
The error is a result of a ViewState problem. This telerik forum thread provides a possible solution: www.telerik.com/community/forums/aspnet-ajax/docking/failed-to-load-view-state-error-when-moving-dynamically-created-widgets-around-the-raddocklayout.aspx