SQL Server : very rare Transaction Commit Issue - asp.net

I am developing a web application with ASP.NET 4.0 with VB.NET as codebehind.
I am using SQL Server 2008 R2 as backend.
I am experiencing very rare problem on a page in my project.
I am entering around two hundred data in textboxes in Telerik Radgrid.
All these information is going to be saved in the database table. When Its saved for the first time, it is working fine and saved in the same order as it is displayed in the grid.
But when I try to update it sometime later, the last row of the grid, it is saved sometimes(not every time) second last in the table. I don't know why and this is my problem I want answer for.
I want the data to stored exactly in the same order as displayed in the grid.
But on update, I find problem with this last row of grid, which is saved second last in table when I commit transaction, it should be saved last.
I am providing VB.NET code below.
Protected Sub SaveBothGridData()
Dim sb1 As New StringBuilder
Dim tran1 As SqlTransaction
Dim tran2 As SqlTransaction
Dim cn As New SqlConnection(ConfigurationManager.ConnectionStrings("DPMTConnectionString").ConnectionString)
Try
'get the existing datatable
Dim rowIndex As Integer = 0
If ViewState("DT_SR1_section1") IsNot Nothing Then
Dim dtCurrentTable1 As DataTable = DirectCast(ViewState("DT_SR1_section1"), DataTable)
If dtCurrentTable1.Rows.Count > 0 Then
For i As Integer = 0 To dtCurrentTable1.Rows.Count - 1
Dim box1 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox1"), TextBox)
Dim box2 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox2"), TextBox)
Dim box3 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox3"), TextBox)
Dim box4 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox4"), TextBox)
Dim box5 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox5"), TextBox)
Dim box6 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox6"), TextBox)
Dim box7 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox7"), TextBox)
Dim box8 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox8"), TextBox)
Dim box9 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox9"), TextBox)
Dim box10 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox10"), TextBox)
Dim box11 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox11"), TextBox)
Dim box12 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox12"), TextBox)
Dim box13 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox13"), TextBox)
Dim box14 As TextBox = DirectCast(RadGrid1.Items(rowIndex).FindControl("TextBox14"), TextBox)
dtCurrentTable1.Rows(i)("CAT") = box1.Text
dtCurrentTable1.Rows(i)("PTTL") = box2.Text
dtCurrentTable1.Rows(i)("C1") = box3.Text
dtCurrentTable1.Rows(i)("C2") = box4.Text
dtCurrentTable1.Rows(i)("C3") = box5.Text
dtCurrentTable1.Rows(i)("C4") = box6.Text
dtCurrentTable1.Rows(i)("C5") = box7.Text
dtCurrentTable1.Rows(i)("C6") = box8.Text
dtCurrentTable1.Rows(i)("C7") = box9.Text
dtCurrentTable1.Rows(i)("C8") = box10.Text
dtCurrentTable1.Rows(i)("C9") = box11.Text
dtCurrentTable1.Rows(i)("C10") = box12.Text
dtCurrentTable1.Rows(i)("CTTL") = box13.Text
dtCurrentTable1.Rows(i)("DIFF") = box14.Text
rowIndex += 1
sb1.Append(box1.Text & " " & box2.Text & " " & box3.Text & " " & box4.Text & " " & box5.Text & " " & box6.Text & " " & box7.Text & " " & box8.Text & " " & box9.Text & " " & box10.Text & " " & box11.Text & " " & box12.Text & " " & box13.Text & " " & box14.Text & " " & Now.ToString & vbCrLf)
Next
End If
'save datatable to database
Dim shadingno As Integer = 0
shadingno = Me.hdnShadingNo_section1.Value
cn.Open()
tran1 = cn.BeginTransaction
Dim mode As String = String.Empty
If Not Request.QueryString("shadingno") Is Nothing Then
Dim delcmd As New SqlCommand
delcmd.Connection = cn
delcmd.Transaction = tran1
delcmd.CommandType = CommandType.StoredProcedure
delcmd.CommandText = "sp_delete_shading_return_1_entry"
delcmd.Parameters.Add("#shadingno", SqlDbType.Int).Value = Request.QueryString("shadingno")
delcmd.Parameters.Add("#section", SqlDbType.NVarChar).Value = "section1"
delcmd.ExecuteNonQuery()
End If
'If Not Request.QueryString("shadingno") Is Nothing Then
' Dim obj As New db
' Dim str As String = "delete from shading_return_entry_general where shadingno=" & Request.QueryString("shadingno")
' str = str & ";delete from shading_return_entry_details where shadingno=" & Request.QueryString("shadingno")
' obj.insertAll(str)
' obj = Nothing
'End If
'Dim cmd1 As New SqlCommand
'cmd1.Transaction = tran
'cmd1.Connection = cn
'cmd1.CommandType = CommandType.StoredProcedure
'cmd1.CommandText = "sp_add_update_delete_shading_return_entry_general"
'cmd1.Parameters.Add("#mode", SqlDbType.NVarChar).Value = "ADD"
'cmd1.Parameters.Add("#srno", SqlDbType.Int).Value = 0
'cmd1.Parameters.Add("#shadingno", SqlDbType.Int).Value = shadingno
'cmd1.Parameters.Add("#entrytimestamp", SqlDbType.DateTime).Value = Now
'cmd1.Parameters.Add("#approvalstatus", SqlDbType.NVarChar).Value = "NOT APPROVED"
'cmd1.Parameters.Add("#approvaltimestamp", SqlDbType.DateTime).Value = System.Data.SqlTypes.SqlDateTime.Null
'cmd1.ExecuteNonQuery()
Dim cmd2 As New SqlCommand
cmd2.Transaction = tran1
cmd2.Connection = cn
cmd2.CommandType = CommandType.StoredProcedure
cmd2.CommandText = "sp_add_update_delete_shading_return_1_heading_details"
cmd2.Parameters.Add("#mode", SqlDbType.NVarChar).Value = "ADD"
cmd2.Parameters.Add("#shadingno", SqlDbType.Int).Value = shadingno
cmd2.Parameters.Add("#section", SqlDbType.NVarChar).Value = "section1"
cmd2.Parameters.Add("#col1heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol1Heading_section1.Value)
cmd2.Parameters.Add("#col2heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol2Heading_section1.Value)
cmd2.Parameters.Add("#col3heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol3Heading_section1.Value)
cmd2.Parameters.Add("#col4heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol4Heading_section1.Value)
cmd2.Parameters.Add("#col5heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol5Heading_section1.Value)
cmd2.Parameters.Add("#col6heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol6Heading_section1.Value)
cmd2.Parameters.Add("#col7heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol7Heading_section1.Value)
cmd2.Parameters.Add("#col8heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol8Heading_section1.Value)
cmd2.Parameters.Add("#col9heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol9Heading_section1.Value)
cmd2.Parameters.Add("#col10heading", SqlDbType.NVarChar).Value = UCase(Me.hdnCol10Heading_section1.Value)
cmd2.ExecuteNonQuery()
Dim sw As StreamWriter = IO.File.CreateText(Server.MapPath("../ADMIN/") & Now.Day & Now.Month & Now.Year & Now.Hour & Now.Minute & Now.Second & ".txt")
sw.Write(sb1.ToString)
sw.Flush()
sw.Close()
For i = 0 To dtCurrentTable1.Rows.Count - 1
Dim cmd As New SqlCommand
cmd.Transaction = tran1
cmd.Connection = cn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "sp_add_update_delete_shading_return_1_entry_details"
cmd.Parameters.Add("#mode", SqlDbType.NVarChar).Value = "ADD"
cmd.Parameters.Add("#shadingno", SqlDbType.Int).Value = shadingno
cmd.Parameters.Add("#section", SqlDbType.NVarChar).Value = "section1"
cmd.Parameters.Add("#cat", SqlDbType.NVarChar).Value = dtCurrentTable1.Rows(i).Item(0)
cmd.Parameters.Add("#pttl", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(1)
cmd.Parameters.Add("#col1", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(2)
cmd.Parameters.Add("#col2", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(3)
cmd.Parameters.Add("#col3", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(4)
cmd.Parameters.Add("#col4", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(5)
cmd.Parameters.Add("#col5", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(6)
cmd.Parameters.Add("#col6", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(7)
cmd.Parameters.Add("#col7", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(8)
cmd.Parameters.Add("#col8", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(9)
cmd.Parameters.Add("#col9", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(10)
cmd.Parameters.Add("#col10", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(11)
cmd.Parameters.Add("#cttl", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(12)
cmd.Parameters.Add("#diff", SqlDbType.Float).Value = dtCurrentTable1.Rows(i).Item(13)
cmd.ExecuteNonQuery()
Next
tran1.Commit()
'Dim eventMsg As String = "Shading Return entry section1 with shading no " & shadingno & " created"
'Dim obj1 As New com.hemalrathod.dpmt.DatabaseHandling
'obj1.SaveToUserEventLog(Request.Cookies.Item("loginname").Value, "Shading return entry 1 create", eventMsg, Now, Request.Cookies.Item("clientipaddress").Value)
'obj1 = Nothing
'Response.Redirect("Shading_View.aspx")
Else
Response.Write("ViewState is null")
End If
Catch ex As Exception
Response.Write(ex.Message)
Finally
cn.Close()
End Try
End Sub
In the above code, I am creating a transaction to save the data, when updating, I first delete the original data and then saving the new one.
Problem is with only first transaction 'tran1'. I haven't found any problem with 'tran2'.
I think problem is with committing transaction. When its committed, somehow, the last row of grid, is saved second last in the table.
Following is the SQL Server procedure I used
Procedure for deleting the existing data before entering new data
ALTER procedure [dbo].[sp_delete_shading_return_1_entry]
(
#shadingno int,
#section nvarchar(50)
)
as
delete from shading_return_1_heading_details
where shadingno = #shadingno and section = #section
delete from shading_return_1_entry_details
where shadingno = #shadingno and section = #section
delete from shading_return_entry_general
where shadingno = #shadingno
Procedure for entering new heading data(this is not creating any problem)
ALTER procedure [dbo].[sp_add_update_delete_shading_return_1_heading_details]
(
#mode nvarchar(50),
#shadingno int,
#section nvarchar(50),
#col1heading nvarchar(50),
#col2heading nvarchar(50),
#col3heading nvarchar(50),
#col4heading nvarchar(50),
#col5heading nvarchar(50),
#col6heading nvarchar(50),
#col7heading nvarchar(50),
#col8heading nvarchar(50),
#col9heading nvarchar(50),
#col10heading nvarchar(50)
)
as
if #mode='ADD'
begin
insert into shading_return_1_heading_details values(#shadingno, #section, #col1heading, #col2heading, #col3heading, #col4heading, #col5heading, #col6heading, #col7heading, #col8heading, #col9heading, #col10heading)
end
Procedure to store data from radgrid to the table(THIS IS ACTUALLY WHERE ERROR MIGHT BE)
ALTER procedure [dbo].[sp_add_update_delete_shading_return_1_entry_details]
(
#mode nvarchar(50),
#shadingno int,
#section nvarchar(50),
#cat nvarchar(50),
#pttl float,
#col1 float,
#col2 float,
#col3 float,
#col4 float,
#col5 float,
#col6 float,
#col7 float,
#col8 float,
#col9 float,
#col10 float,
#cttl float,
#diff float
)
as
if #mode='ADD'
begin
insert into shading_return_1_entry_details
values(#shadingno, #section, #cat, #pttl, #col1, #col2, #col3, #col4, #col5, #col6, #col7, #col8, #col9, #col10, #cttl, #diff)
end
After this, as per my VB.NET code, I am committing 'tran1' transaction, and then problem occurs sometimes not often.
In short, I want all rows in radgrid to be stored exactly in the same order, but after committing transaction, sometimes, the last row of grid, is stored second last in the table.
How can I solve this?
Thank you in advance

Related

Query string not retrieving data values

Hope you guys could give me some help.
I have a asp.net web form which gets data from SQL database and displays it on webpage via product code number or product description.
Searching by description will display a list of similar products where each list will have a button with the product code when clicked will open another site with extra product information,
e.g.
13892
14589
17485
00010
08890
The problem is all the codes that start from 1 upwards will show more details, but when I click on product codes that start with 0 such as 00010, 08890 will show no data when in fact there should be data.
Any help would be appreciated.
code I have below,
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Val(Request.QueryString("Stock_code")) <> 0 Then
Dim dt As DataTable = New DataTable
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description], STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as [Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as [Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM dbo.STK_STOCK WHERE STKCODE = '" & Val(Request.QueryString("Stock_code")) & "'"
Dim strQUery2 As String = "SELECT LOC_CODE as [Location_Code], LOC_NAME as [Location], LOC_PHYSICAL as [Physical_Stock] FROM dbo.STK_LOCATION WHERE LOC_CODE IN ('WH01','WH03','WH04','WH08','WH11')" & _
"AND LOC_STOCK_CODE = '" & Val(Request.QueryString("Stock_code")) & "'"
Dim strQuery3 As String = "SELECT STKLANG_STOCKNAME as [Chinese_Description] FROM dbo.STK_STOCK_LANG WHERE STKLANG_STOCKCODE ='" & Val(Request.QueryString("stock_code")) & "'"
Dim strQuery4 = "SELECT STK_SELLPRICE1 as [Retail_Price], STK_SELLPRICE5 as [Retail_Rest_Split] FROM dbo.STK_STOCK_2 WHERE STKCODE2 = '" & Val(Request.QueryString("stock_code")) & "'"
Using cmd4 As SqlCommand = New SqlCommand(strQuery4)
Dim da3 As SqlDataAdapter = New SqlDataAdapter
Dim dt4 As New DataTable
cmd4.Connection = cnn : cnn.Open()
da3.SelectCommand = cmd4
da3.Fill(dt4)
For i = 0 To dt4.Rows.Count - 1
Label8.Text = dt4.Rows(i).Item("Retail_Rest_Split")
Next
End Using
cnn.Close()
Using cmd As SqlCommand = New SqlCommand(strQuery)
Dim sda As SqlDataAdapter = New SqlDataAdapter
cmd.Connection = cnn : cnn.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
For i = 0 To dt.Rows.Count - 1
Label7.Text = dt.Rows(i).Item("Stock_Code")
Label1.Text = dt.Rows(i).Item("Notes")
Label3.Text = dt.Rows(i).Item("Retail_Price")
Label4.Text = dt.Rows(i).Item("Pack_Size")
Label5.Text = dt.Rows(i).Item("Stock_Description")
'Label8.Text = dt.Rows(i).Item("Pack_Size")
Label9.Text = dt.Rows(i).Item("Net_Weight")
Label10.Text = dt.Rows(i).Item("Gross_Weight")
GridView1.DataSource = dt
GridView1.DataBind()
Next
End Using
cnn.Close()
Dim dt3 As DataTable = New DataTable
Using cmd3 As SqlCommand = New SqlCommand(strQuery3)
Dim da2 As SqlDataAdapter = New SqlDataAdapter
cmd3.Connection = cnn : cnn.Open()
da2.SelectCommand = cmd3
da2.Fill(dt3)
End Using
For i = 0 To dt3.Rows.Count - 1
Label6.Text = dt3.Rows(i).Item("Chinese_Description")
Next
Dim cmd2 As New SqlCommand
Dim dt2 As New DataTable
Dim da As New SqlDataAdapter
With cmd2
.Connection = cnn
.CommandText = strQUery2
End With
da.SelectCommand = cmd2
da.Fill(dt2)
GridView1.DataSource = dt2
GridView1.DataBind()
End If
End Sub
You want to use a paramaterized query like this (I'm going to fold that query string to make it more readable without having to scroll horizontally):
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description],
STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as
[Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as
[Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM
dbo.STK_STOCK WHERE STKCODE = #StockCode"
Using cmd As New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("#StockCode", Request.QueryString("Stock_code"))
' Do your other stuff here.
End Using
Note, that you don't want to just use string concatenation to insert your query parameter. That opens you up to SQL injection attacks.
Instead, you use a placeholder in your query like #StockCode. Then you call AddWithValue on the command to give it the value of that parameter.
You can also explicitly specify the parameter type if you need to:
' Add CustomerID parameter for WHERE clause.
command.Parameters.Add("#ID", SqlDbType.Int)
command.Parameters("#ID").Value = customerID
Assuming they are all 5 digit codes, this will make sure the stock code is numeric.
Replace
Val(Request.QueryString("Stock_code"))
with
String.Format("{0:00000}", Integer.Parse(Request.QueryString("Stock_code")))
Will raise an exception if Request.QueryString("Stock_code") is not parsed as integer, which prevents against malicious injection.
For example:
Dim stockCode = String.Format("{0:00000}", Integer.Parse(Request.QueryString("Stock_code")))
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description], STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as [Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as [Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM dbo.STK_STOCK WHERE STKCODE = '" & stockCode & "'"
Dim strQUery2 As String = "SELECT LOC_CODE as [Location_Code], LOC_NAME as [Location], LOC_PHYSICAL as [Physical_Stock] FROM dbo.STK_LOCATION WHERE LOC_CODE IN ('WH01','WH03','WH04','WH08','WH11')" & "AND LOC_STOCK_CODE = '" & stockCode & "'"
Dim strQuery3 As String = "SELECT STKLANG_STOCKNAME as [Chinese_Description] FROM dbo.STK_STOCK_LANG WHERE STKLANG_STOCKCODE ='" & stockCode & "'"
Dim strQuery4 = "SELECT STK_SELLPRICE1 as [Retail_Price], STK_SELLPRICE5 as [Retail_Rest_Split] FROM dbo.STK_STOCK_2 WHERE STKCODE2 = '" & stockCode & "'"
#dwilliss has just answered the question using parameters, which is probably better than my method. Posting this anyway

Trying to access only one textbox field inside a repeater template

If (dr.Read) Then
Dim thread As Integer
thread = Convert.ToInt32(dr(0).ToString())
For Each rItem As RepeaterItem In Repeater1.Items
Dim txtBox As HtmlInputText = DirectCast(rItem.FindControl("messtxt"), HtmlInputText)
If Not IsNothing(txtBox) Then
Dim messtxta As String = txtBox.Value
cmd2 = New OleDbCommand("INSERT INTO messages(content) VALUES('" & messtxta.Replace("'", "''") & "')", con)
cmd2.Connection = con
cmd2.ExecuteNonQuery()
End If
Next
Response.Redirect("pals.aspx")
The above code works finely for inserting purposes.
Except:
The problem is, if the repeater repeats x number of times, there will be x number of inserts from the textbox, out of which one will be the one I entered.
I only want it to insert one time.
Please help.
If (dr.Read) Then
Dim thread As Integer
Dim txtBox As HtmlInputText
Dim messtxta As String
thread = Convert.ToInt32(dr(0).ToString())
For Each rItem As RepeaterItem In Repeater1.Items
txtBox = DirectCast(rItem.FindControl("messtxt"), HtmlInputText)
If Not IsNothing(txtBox) Then
IF txtBox.Value.Length > 0 THEN
messtxta = txtBox.Value
END IF
End If
Next
cmd2 = New OleDbCommand("INSERT INTO messages(content) VALUES('" & messtxta.Replace("'", "''") & "')", con)
cmd2.Connection = con
cmd2.ExecuteNonQuery()
Response.Redirect("pals.aspx")

Why I get SQL error message based on Div color style?

I was verify if the boolean is True or False. If it false, it will change the server Name text to color red, if True, it doesn't change color. The SQL was able to read server Name that doesn't change text color but couldn't read the server Name colored red text and got SQL error message,
System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near 'red'.
Here is the VB code:
Dim sqlConn As New System.Data.SqlClient.SqlConnection((ConfigurationManager.ConnectionStrings("SOCT").ConnectionString))
Dim strSqlSecondary As String = "SELECT [Name], [Compliance] FROM [dbo].[ServerOwners] where SecondaryOwner like #uid order by [name]"
Dim cmdSecondary As New System.Data.SqlClient.SqlCommand(strSqlSecondary, sqlConn)
cmdSecondary.Parameters.AddWithValue("#uid", TNN.NEAt.GetUserID())
Dim dr As System.Data.SqlClient.SqlDataReader
Try
sqlConn.Open()
Dim root As TreeNode
Dim rootNode As TreeNode
Dim firstNode As Integer = 0
'Load Primary Owner Node
'Create RootTreeNode
dr = cmdSecondary.ExecuteReader()
If dr.HasRows Then
'Load Secondary Owner Node
'Create RootTreeNode
root = New TreeNode("Secondary Owner", "Secondary Owner")
TreeViewGroups.Nodes.Add(root)
root.SelectAction = TreeNodeSelectAction.None
rootNode = TreeViewGroups.Nodes(firstNode)
'populate the child nodes
While dr.Read()
Dim child As TreeNode = New TreeNode(dr("Name"), dr("Name"))
Dim complianceFlag As Boolean
If Boolean.TryParse(dr("Compliance"), complianceFlag) Then
' Yes, compliance value is a Boolean, now set color based on value
If Not complianceFlag Then
child.Text = "<div style='color:red'>" + child.Text + "</div>"
End If
End If
rootNode.ChildNodes.Add(child)
child.SelectAction = TreeNodeSelectAction.None
End While
dr.Close()
The error came from this line code because it read "red":
child.Text = "<div style='color:red'>" + child.Text + "</div>"
The child node text is passing when I click link to update,
Protected Sub LinkButtonConfirm_Click(sender As Object, e As System.EventArgs) Handles LinkButtonConfirm.Click
hide()
PanelCompliance.Visible = True
PanelDisplayGrid.Visible = True
'display the servers
Dim sqlConn As New System.Data.SqlClient.SqlConnection((ConfigurationManager.ConnectionStrings("SOCT").ConnectionString))
Dim strSql As New StringBuilder
strSql.Append("Select [Name] , [ApplicationName] , [Environment], [Description], [TechMgmtTeam] , [PrimaryOwner], [PPhone], [SecondaryOwner], [SPhone], [Queue], [Crit] from dbo.ServerOwners where")
'Loops Through all Selected items and appends to sql statement
Dim x As Integer = 0
For Each item As TreeNode In TreeViewGroups.CheckedNodes
If item.Depth = 0 Then
Else
'append to select statement
strSql.Append(" [Name]='" & item.Text & "' or ")
x = x + 1
End If
Next
If x = 0 Then
hide()
LabelError.Text = "Please select at least one server in the left pane."
PanelError.Visible = True
Else
strSql.Append(" [Name]='Blank' order by [name]")
Try
sqlConn.Open()
Dim cmd As New System.Data.SqlClient.SqlCommand(strSql.ToString(), sqlConn)
Dim a As New SqlClient.SqlDataAdapter(cmd)
Dim datTab As New DataTable
a.Fill(datTab)
Session("Table") = datTab
GridViewDisp.DataSource = datTab
GridViewDisp.DataBind()
Catch ex As Exception
hide()
LabelError.Text = ex.ToString()
PanelError.Visible = True
Finally
sqlConn.Close()
sqlConn.Dispose()
End Try
End If
End Sub
If I get rid of Div tag, everything is work fine except there won't be colored red. How they able to read Div style which they should ignore the style and focus on child text. Is there a way to fix?
If you store the Name in the .Tag property of the child, you get to be able to use it regardless of what you do to the .Text of the child:
While dr.Read()
Dim myName as String = dr("Name")
Dim child As TreeNode = New TreeNode(myName , myName)
child.Tag = myName
Then in LinkButtonConfirm_Click
Dim x As Integer = 0
For Each item As TreeNode In TreeViewGroups.CheckedNodes
If item.Depth <> 0 Then
'append to select statement
strSql.Append(" [Name]='" & CStr(item.Tag) & "' or ")
x = x + 1
End If
Next
But you should still be adding the CStr(item.Tag) as SQL parameters. You already have a counter x in the loop which you can use to construct parameter names ("#p0", "#p1" etc.).
Edit: which would result in the Click handler looking something like
Protected Sub LinkButtonConfirm_Click(sender As Object, e As System.EventArgs) Handles LinkButtonConfirm.Click
hide()
PanelCompliance.Visible = True
PanelDisplayGrid.Visible = True
'display the servers
Dim sqlConn As New System.Data.SqlClient.SqlConnection((ConfigurationManager.ConnectionStrings("SOCT").ConnectionString))
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim strSql As New StringBuilder
Dim qryBase = <sql>
SELECT [Name]
,[ApplicationName]
,[Environment]
,[Description]
,[TechMgmtTeam]
,[PrimaryOwner]
,[PPhone]
,[SecondaryOwner]
,[SPhone]
,[Queue]
,[Crit]
FROM dbo.ServerOwners
WHERE
</sql>.Value
strSql.Append(qryBase & " ")
'Loop through all Selected items and append to sql statement
Dim x As Integer = 0
Dim nLastCheckedNode As Integer = TreeViewGroups.CheckedNodes.Count - 1
For Each item As TreeNode In TreeViewGroups.CheckedNodes
If item.Depth <> 0 Then
'append to select statement
Dim paramName As String = "#p" & x.ToString()
strSql.Append("[Name] = " & paramName)
If x <> nLastCheckedNode Then
' we have another node to look at, so add " OR "
strSql.Append(" OR ")
End If
'TODO: set the correct SqlDbType and the correct .Size
cmd.Parameters.Add(New SqlParameter With {.ParameterName = paramName,
.SqlDbType = SqlDbType.NVarChar,
.Size = 20,
.Value = CStr(item.Tag)})
x += 1
End If
Next
If x = 0 Then
hide()
LabelError.Text = "Please select at least one server in the left pane."
PanelError.Visible = True
Else
strSql.Append(" ORDER BY [Name]")
Try
sqlConn.Open()
cmd.Connection = sqlConn
cmd.CommandText = strSql.tostring()
Dim a As New SqlClient.SqlDataAdapter(cmd)
Dim datTab As New DataTable
a.Fill(datTab)
Session("Table") = datTab
GridViewDisp.DataSource = datTab
GridViewDisp.DataBind()
Catch ex As Exception
hide()
LabelError.Text = ex.ToString()
PanelError.Visible = True
Finally
sqlConn.Close()
sqlConn.Dispose()
End Try
End If
End Sub
#Andrew Morton - Your theory are correct about error in strSql.Append(" [Name]='" & item.Text & "' or ") in LinkButtonConfirm_Click. I changed to strSql.Append(" [Name]='" & item.Value & "' or ") by replacing Text to Value. Now everything worked!

ASP.net placing database model numbers into an array

Hey all i am trying to figure out how to add some of my model numbers from my database to am array while looping.
This is my code:
objCmd = New MySqlCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
If dtReader.HasRows() Then
grdViewItems.DataSource = dtReader
grdViewItems.DataBind()
Dim arrayOfItems As String() = New String() {}
While dtReader.Read()
arrayOfItems(intX) = dtReader.GetString("model_number")
'arrayItems(intX) = dtReader.GetString("model_number")
intX += 1
End While
'Session.Add("arrayOfItems", arrayItems)
Session("arrayOfItems") = arrayOfItems
dtReader.Close()
dtReader = Nothing
objConn.Close()
objConn = Nothing
End If
Problem being that it never populates the array with the values (although the values are present in the gridview because it skips the reading of the values in the while loop.
What am i doing incorrectly here?
Complete code
Dim intX As Integer = 0
objConn = New MySqlConnection(product.strConnString)
objConn.Open()
strSQL = "SELECT prod.id, PP.model_number, description, price, price_new, price_direct, price_builder " & _
"FROM product as prod " & _
"INNER JOIN product_price as PP ON PP.product_id = prod.type " & _
"WHERE prod.id = " & pageID & ";"
Try
objCmd = New MySqlCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
If dtReader.HasRows() Then
grdViewItems.DataSource = dtReader
grdViewItems.DataBind()
Dim arrayOfItems As New List(Of String)()
For Each row As GridViewRow In grdViewItems.Rows
arrayOfItems(intX) = row.Cells(0).Text.ToString
intX = intX + 1
Next
MsgBox(arrayOfItems(0))
'Session.Add("arrayOfItems", arrayItems)
Session("arrayOfItems") = arrayOfItems
dtReader.Close()
dtReader = Nothing
objConn.Close()
objConn = Nothing
End If
Catch ex As Exception
MsgBox("LoadProductItems: " & ex.Message)
End Try
Instead of array, I would recommend using List of int or string
It looks like the problem is in your loop. Replace the following code
Do While dtReader.Read
arrayOfItems(intX) = dtReader.GetString("model_number")
intX += 1
Loop
'with this code
While dtReader.Read()
arrayOfItems(intX) = dtReader.GetString("model_number")
intX += 1
End While
Updated Answer:
When you assign data to gridview then also save the data in a datatable like this
Dim dt As DataTable = New DataTable
dt = dtReader
`Then get the data from the table
Dim i As Integer = 0
Do While (i < dt.Rows.Count)
dt.Rows(i)("COlumnName").ToString
i = (i + 1)
Loop
Again Updated Answer:
Read the data from the gridview
For Each row As GridViewRow In grdViewItems.Rows
arrayOfItems(intX) = row.Cells(0).Text.ToString ` in cell specify the index of the model_number column
intX = intX + 1
Next

Running a Query, getting a value, then update record in ASP.net (VB)

Honest, I am really trying to learn this stuff. I've been using Classic ASP for years and just switching over to .net. So far, I'm not having much fun, but I'm trying and I'm not going to quit. One of the small pieces I am struggling with is running a query then, updating the record. Even googling for examples, I having a tough time figuring out how to do something simple like:
Set objRS = Server.CreateObject ("ADODB.RecordSet")
ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=G:\Inetpub\wwwroot\TestPage\TheData\TestData.mdb;" & _
"Persist Security Info=False"
SqlStr = "SELECT * " & _
"FROM Techs " & _
"WHERE UserID = " & UserID & " "
objrs.Open SqlStr, ConStr, adOpenStatic, adLockOptimistic,adCmdText
If Objrs.recordCount <> 0 Then
TechUserName = Objrs("TechUserName")
Objrs.Update
Objrs("LastLogin") = Now()
Objrs.Update
Else
Objrs.AddNew
Objrs("UserID") = UserID
Objrs.Update
End If
Objrs.Close
Set objRS = Nothing
Is it even possible? Can someone please help me do the above code in ASP.net (VB) or point me to a really good thorough tutorial on how to do this.
Thanks in advance.
ah.. first off - you are trying to do classic vb stuff with .net.
Scrap it. There are no more cursors. Its client side data you basically get back in a dataset or a data reader (or a single value)
See roughly:
http://msdn.microsoft.com/en-us/library/bh8kx08z%28v=VS.100%29.aspx
They miss the spot where they get a connection, which is basically
Dim connection as New SqlConnection("server=localhost;uid=username;pwd=whatver;")
make sure you dispose of everything when done
connection.Dispose()
once you have your dataset back - just (c# syntax)
foreach(DataRow row in yourDataSet.Tables[0].Rows)
{
Debug.WriteLine(row["YourFieldName"])
}
For a data reader, see:
http://www.developerfusion.com/article/4278/using-adonet-with-sql-server/2/
The difference is a dataset has ALL data loaded on the client side. Quite a bit different than the server side cursor stuff with ado.
A DataReader will stream the results as you scroll through them - the overhead of forming this large dataset in memory isn't there so its a bit faster.
hope this gets you started - remember SCRAP the ADO stuff. Its not used anymore.
Woo Hoo I got it!
Dim SqlStr As String
Dim ConStr As String = ConfigurationManager.ConnectionStrings("TCConStr").ConnectionString
SqlStr = "SELECT * " & _
"FROM TechUsers " & _
"WHERE TechWWID = " & Chr(34) & TechWWID & Chr(34) & " " & _
"AND TechEmplNum = " & TechEmplNum & " "
Dim CN As OleDbConnection = New OleDbConnection(ConStr)
CN.Open()
Dim DA As OleDbDataAdapter = New OleDbDataAdapter(SqlStr, CN)
Dim DS As New DataSet
DA.Fill(DS, "TechUsers")
Dim DT As DataTable = DS.Tables("TechUsers")
Dim RecCount As Integer = DT.Rows.Count
Dim CB As OleDbCommandBuilder = New OleDbCommandBuilder(DA)
If RecCount = 0 Then
DA.InsertCommand = CB.GetInsertCommand()
Dim DR As DataRow = DT.NewRow()
DR("TechName") = TechName
DR("TechWWID") = TechWWID
DR("TechEmplNum") = TechEmplNum
DR("FirstLogin") = Date.Now()
DR("LastLogin") = Date.Now()
DR("LoginCount") = 1
DT.Rows.Add(DR)
DA.Update(DS, "TechUsers")
Else
Dim DR As DataRow = DT.Rows(0)
Dim LoginCount As Integer = DR("LoginCount")
TestStuff.InnerHtml = TestStuff.InnerHtml & "<br > " & LoginCount
DA.UpdateCommand = CB.GetUpdateCommand()
DR("LastLogin") = Date.Now()
DR("LoginCount") = LoginCount + 1
DA.Update(DS, "TechUsers")
End If
CN.Close()
Thanks everyone for the clues to get this done.
Do as NoAlias told you, but watch out not make a false start.
Forget about inserting text into your SQL, remember that quotes have to doubled, etc.
Try the parameterized sql statements, like in this sample:
I have a table with 4 colunms, CollCode and CollSeq are the key, TermType and TermText are the modifiable data
The code explains how to insert, update or delete a row with parameters instaed if textvalues in the SQL.
The code is valid only for ACCESS, SQL SERVER or MYSQL require different code for the template and have different DbTypes
in the first part of the program:
' select
Dim SQLaxSelect As String = "SELECT DISTINCT CollSeq FROM SearchTerms WHERE CollCode = ? ORDER BY CollSeq"
Dim DRaxSelect As OleDbDataReader = Nothing
Dim DCaxSelect As OleDbCommand
Dim axSelP1 As New OleDbParameter("#CollCode", OleDbType.VarChar, 4)
DCaxSelect = New OleDbCommand(SQLaxSelect, DbConn)
DCaxSelect.Parameters.Add(axSelP1)
' Insert
Dim DbConn As New OleDbConnection(SqlProv)
Dim SQLTwInsert As String = "INSERT INTO SearchTerms (CollCode, CollSeq, TermType, TermText) VALUES (?, ?, ?, ?)"
Dim DRTwInsert As OleDbDataReader = Nothing
Dim DCCTwInsert As OleDbCommand
Dim TwInsP1 As New OleDbParameter("#CollCode", OleDbType.VarChar, 4)
Dim TwInsP2 As New OleDbParameter("#CollSeq", OleDbType.Integer, 4)
Dim TwInsP3 As New OleDbParameter("#TermType", OleDbType.VarChar, 4)
Dim TwInsP4 As New OleDbParameter("#TermText", OleDbType.VarChar, 255)
DCCTwInsert = New OleDbCommand(SQLTwInsert, DbConn)
DCCTwInsert.Parameters.Add(TwInsP1)
DCCTwInsert.Parameters.Add(TwInsP2)
DCCTwInsert.Parameters.Add(TwInsP3)
DCCTwInsert.Parameters.Add(TwInsP4)
' Delete
Dim SQLTwDelete As String = "DELETE FROM SearchTerms WHERE CollCode = ? AND CollSeq = ? AND TermType = ? AND TermText = ?"
Dim DRTwDelete As OleDbDataReader = Nothing
Dim DCCTwDelete As OleDbCommand
Dim TwDelP1 As New OleDbParameter("#CollCode", OleDbType.VarChar, 4)
Dim TwDelP2 As New OleDbParameter("#CollSeq", OleDbType.Integer, 4)
Dim TwDelP3 As New OleDbParameter("#TermType", OleDbType.VarChar, 4)
Dim TwDelP4 As New OleDbParameter("#TermText", OleDbType.VarChar, 255)
DCCTwDelete = New OleDbCommand(SQLTwDelete, DbConn)
DCCTwDelete.Parameters.Add(TwDelP1)
DCCTwDelete.Parameters.Add(TwDelP2)
DCCTwDelete.Parameters.Add(TwDelP3)
DCCTwDelete.Parameters.Add(TwDelP4)
' Update
Dim SQLTwUpdate As String = "UPDATE SearchTerms SET TermType = ?, TermText = ? WHERE CollCode = ? AND CollSeq = ? AND TermType = ? AND TermText = ?"
Dim DRTwUpdate As OleDbDataReader = Nothing
Dim DCCTwUpdate As OleDbCommand
Dim TwUpdP1 As New OleDbParameter("#TermType", OleDbType.VarChar, 4)
Dim TwUpdP2 As New OleDbParameter("#TermText", OleDbType.VarChar, 255)
Dim TwUpdP3 As New OleDbParameter("#CollCode", OleDbType.VarChar, 4)
Dim TwUpdP4 As New OleDbParameter("#CollSeq", OleDbType.Integer, 4)
Dim TwUpdP5 As New OleDbParameter("#oldTermType", OleDbType.VarChar, 4)
Dim TwUpdP6 As New OleDbParameter("#oldTermText", OleDbType.VarChar, 255)
DCCTwUpdate = New OleDbCommand(SQLTwUpdate, DbConn)
DCCTwUpdate.Parameters.Add(TwUpdP1)
DCCTwUpdate.Parameters.Add(TwUpdP2)
DCCTwUpdate.Parameters.Add(TwUpdP3)
DCCTwUpdate.Parameters.Add(TwUpdP4)
DCCTwUpdate.Parameters.Add(TwUpdP5)
DCCTwUpdate.Parameters.Add(TwUpdP6)
in the processing part of the program:
'select
axSelP1.Value = requested key value CollCode
Try
DRaxSelect = DCaxSelect.ExecuteReader()
Do While (DRaxSelect.Read())
'get value, first SELECTed value has index 0
CollSeq = GetDbIntegerValue(DRaxSelect, 0) ' routine to convert NULL in 0
Loop
Catch ex As Exception
your type of report exception
Finally
If Not (DRaxSelect Is Nothing) Then
DRaxSelect.Dispose()
DRaxSelect.Close()
End If
End Try
' Update
TwUpdP1.Value = new value TermType
TwUpdP2.Value = new value TermText
TwUpdP3.Value = key value CollCode
TwUpdP4.Value = key value CollSeq
TwUpdP5.Value = old value TermType to avoid updating a row that 1 millisecond earlier was modified by someone else
TwUpdP6.Value = old value TermText
Try
DRTwUpdate = DCCTwUpdate.ExecuteReader()
Catch ex As Exception
your type of report exception
Finally
If Not (DRTwUpdate Is Nothing) Then
DRTwUpdate.Dispose()
DRTwUpdate.Close()
End If
End Try
' Insert
TwInsP1.Value = new key value CollCode
TwInsP2.Value = new key value CollSeq
TwInsP3.Value = value TermType
TwInsP4.Value = value TermText
Try
DRTwInsert = DCCTwInsert.ExecuteReader()
Catch ex As Exception
your type of report exception
Finally
If Not (DRTwInsert Is Nothing) Then
DRTwInsert.Dispose()
DRTwInsert.Close()
End If
End Try
' Delete
TwDelP1.Value = key value CollCode
TwDelP2.Value = key value CollSeq
TwDelP3.Value = old value TermType to avoid deleting a row that 1 millisecond earlier was modified by someone else
TwDelP4.Value = old value TermText
Try
DRTwDelete = DCCTwDelete.ExecuteReader()
Catch ex As Exception
your type of report exception
Finally
If Not (DRTwDelete Is Nothing) Then
DRTwDelete.Dispose()
DRTwDelete.Close()
End If
End Try
my routine (in a Module)
Friend Function GetDbIntegerValue(ByVal Dr As OleDbDataReader, ByVal nr As Integer) As Integer
If IsDBNull(Dr.Item(nr)) Then
Return 0
Else
Return Dr.GetInt32(nr)
End If
End Function

Resources