ASP.net placing database model numbers into an array - asp.net

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

Related

How to iterate between two datatables in ASP.NET

I have two datatables (dtSF and CurveFitTable) that contain two different values which I have to multiply. The objective is to produce a datatable that contains the product of two values from two different datatables. The twist is, the CurveFitTable came from different csv files in a directory which I already defined.
What I intended to do is to have a datatable like the adjustedCopy table in the image below. Unfortunately, what I'm getting is a single datatable which kept on being overwritten and whenever I attempt to databind it to the grid, the datatable seems to be empty. Please help. T.T
This is my code:
Dim adjusteddemandtable As New DataTable()
Dim adjustedcopy As New DataTable()
Dim multiply_SF As Double
Dim adjusted_Demand As Double
Dim initial_Demand As Double
Dim basecurvestamp As Date
adjusteddemandtable.Columns.Add("Base Curve", GetType(Date))
adjusteddemandtable.Columns("Base Curve").SetOrdinal(0)
adjusteddemandtable.Columns.Add("Adjusted_Demand", GetType(Double))
Dim CurveFitTatble As New DataTable()
Try
For Each filename As String In System.IO.Directory.GetFiles(BackUpDirectory)
CurveFitTatble = GetDataTabletFromCSVFile(filename)
For Each row2 As DataRow In dtSF.Rows()
For Each row As DataRow In CurveFitTatble.Rows()
initial_Demand = row(1)
basecurvestamp = row(0)
multiply_SF = row2(0)
adjusted_Demand = multiply_SF * initial_Demand
Dim rowa As DataRow = adjusteddemandtable.Rows.Add()
rowa(0) = basecurvestamp
rowa(1) = adjusted_Demand
Next
Next
adjustedcopy.Merge(adjusteddemandtable, True, MissingSchemaAction.AddWithKey)
Next
GridView1.DataSource = adjustedcopy
GridView1.DataBind()
Catch ex As Exception
ErrorMessageBox(ex.Message)
End Try
I think, I'm missing something or overlooked an important step. Please advise. Thanks in advance.
I just did what #jmcilhinney told me (that is to replace nested Foreach nested loop. Here is my new code (and fortunately, it is working as its expected output requires)
Try
Dim y As Integer = System.IO.Directory.GetFiles(BackUpDirectory).Length
Dim row1 As DataRow
Dim i As Integer = 0
While i < y
row1 = dtSF.Rows(i)
Dim filenames As String() = System.IO.Directory.GetFiles(BackUpDirectory)
Dim filename As String = filenames(i)
multiply_SF = row1(0)
CurveFitTatble = New DataTable()
Dim TS_Name As String = "TmeStamp" + "_" & i
Dim AD_Name As String = "AdjustedDemand" + "_" & i
If i = 0 Then
adjusteddemandtable.Columns.Add(TS_Name, GetType(Date))
adjusteddemandtable.Columns(TS_Name).SetOrdinal(i)
adjusteddemandtable.Columns.Add(AD_Name, GetType(Double))
adjusteddemandtable.Columns(AD_Name).SetOrdinal(i + 1)
ElseIf i > 0 Then
adjusteddemandtable.Columns.Add(TS_Name, GetType(Date))
adjusteddemandtable.Columns(TS_Name).SetOrdinal(i + 1)
adjusteddemandtable.Columns.Add(AD_Name, GetType(Double))
adjusteddemandtable.Columns(AD_Name).SetOrdinal(i + 2)
End If
'If row1(0) = filename Then
CurveFitTatble = GetDataTabletFromCSVFile(filename)
'For Each row As DataRow In CurveFitTatble.Rows()
Dim row As DataRow
For j As Integer = 0 To CurveFitTatble.Rows.Count - 1
row = CurveFitTatble.Rows(j)
initial_Demand = row(1)
basecurvestamp = row(0)
adjusted_Demand = multiply_SF * initial_Demand
Dim rowa As DataRow = adjusteddemandtable.Rows.Add()
If i = 0 Then
rowa(i) = basecurvestamp
rowa(i + 1) = adjusted_Demand
ElseIf i > 0 Then
rowa(i + 1) = basecurvestamp
rowa(i + 2) = adjusted_Demand
End If
Next
i = i + 1
End While
Catch ex As Exception
ErrorMessageBox(ex.Message)
End Try

SQL Server : very rare Transaction Commit Issue

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

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!

Customized ToolTip on MSChart Data

I'm trying to show a 'customized' ToolTip on an MSChart on an asp.net page, using vb.net
The chart displays OK, but I'm trying to get it to show the 'YEAR' as part of the tooltip, as well as the XY values.
I can't figure out how to do it.
Here's the code that I'm using to build the chart:
dt = New DataTable
dt.Columns.Add("Topic")
dt.Columns.Add("Value")
dt.Columns.Add("Year")
For i = 0 To t_YEARS.Count - 1
Sql = "SELECT att_Topic, att_Value, att_Year from Att "
Sql += " WHERE att_Year = '" & t_YEARS(i) & "' "
conn.ConnectionString = strConnString
conn.Open()
cmd = New SqlCommand(Sql, conn)
dr = cmd.ExecuteReader
While dr.Read
dt.Rows.Add(dr(0), dr(1), dr(2))
End While
dr.Close()
cmd.Dispose()
conn.Close()
Next
Chart1.DataSource = dt
Chart1.Series("Series1").XValueMember = "Topic"
Chart1.Series("Series1").YValueMembers = "Value"
Chart1.Series("Series1").ToolTip = "#VALX - #VALY"
Chart1.ChartAreas("ChartArea1").Area3DStyle.Enable3D = True
Chart1.DataBind()
Well, there may be a better answer, but I figured out a work-around anyhow ... I'm adding the YEAR to the axislabel. Then, in chart1_customize, changing the color of the bar, based on different axislabel. Seems to work.
dt = New DataTable
dt.Columns.Add("Topic")
dt.Columns.Add("Value")
dt.Columns.Add("Year")
For i = 0 To t_YEARS.Count - 1
showDATA = False
Sql = "SELECT att_Topic, att_Value, att_Year, att_Data from BWS_Att "
If (RBL_LIMIT.SelectedValue = 1) Then
showDATA = True
Sql += " WHERE att_Attrib = 'Location' "
Sql += " AND att_Data IN ('" & String.Join("','", t_LOCS) & "')"
ElseIf (RBL_LIMIT.SelectedValue = 2) Then
showDATA = True
Sql += " WHERE att_Attrib = 'Department' "
Sql += " AND att_Data IN ('" & String.Join("','", t_DEPTS) & "')"
Else
Sql += " WHERE att_Attrib = 'Company' "
End If
Sql += " AND att_Year = '" & t_YEARS(i) & "' "
Sql += " AND att_Topic IN ('" & String.Join("','", t_CATS) & "')"
Sql += " Order By att_ind"
conn.ConnectionString = strConnString
conn.Open()
cmd = New SqlCommand(Sql, conn)
dr = cmd.ExecuteReader
While dr.Read
'dt.Rows.Add(dr(0), dr(1), dr(2))
thisYR = dr(2).ToString
If (lastYR <> thisYR) Then
Chart1.Series("Series1").Points.Add(vbEmpty)
Chart1.Series("Series1").Points.Add(vbEmpty)
lastYR = thisYR
End If
If (showDATA = True) Then
Chart1.Series("Series1").Points.AddXY(dr(2).ToString & "|" & dr(3).ToString & ":" & dr(0).ToString, dr(1))
Else
Chart1.Series("Series1").Points.AddXY(dr(2).ToString & ":" & dr(0).ToString, dr(1))
End If
Chart1.Series("Series1").ToolTip = " #AXISLABEL | #VALY"
End While
dr.Close()
cmd.Dispose()
conn.Close()
Next
~~~~~~~~~~
Private Sub Chart1_Customize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Chart1.Customize
Dim C() As Drawing.Color = { _
Drawing.Color.Khaki, _
Drawing.Color.DarkSalmon, _
Drawing.Color.Goldenrod, _
Drawing.Color.MediumAquamarine, _
Drawing.Color.Tan _
}
Dim CN As Int16 = 0
Dim thisC As Int16 = 0
Dim LAST As String = String.Empty
For Each dp As System.Web.UI.DataVisualization.Charting.DataPoint In Chart1.Series("Series1").Points
Dim x As Array = dp.AxisLabel.Split(":")
If (x(0) <> "") Then
Dim H As String = x(0)
If (LAST <> H) Then
CN += 1
LAST = H
thisC = (CN Mod 5)
End If
dp.Color = C(thisC)
End If
Next
End Sub

Invalid Cast Exception with Update Panel

On Button Click
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
MsgBox("INSIDE")
If SocialAuthUser.IsLoggedIn Then
Dim accountId As Integer = BLL.getAccIDFromSocialAuthSession
Dim AlbumID As Integer = BLL.createAndReturnNewAlbumId(txtStoryTitle.Text.Trim, "")
Dim URL As String = BLL.getAlbumPicUrl(txtStoryTitle.Text.Trim)
Dim dt As New DataTable
dt.Columns.Add("PictureID")
dt.Columns.Add("AccountID")
dt.Columns.Add("AlbumID")
dt.Columns.Add("URL")
dt.Columns.Add("Thumbnail")
dt.Columns.Add("Description")
dt.Columns.Add("AlbumCover")
dt.Columns.Add("Tags")
dt.Columns.Add("Votes")
dt.Columns.Add("Abused")
dt.Columns.Add("isActive")
Dim Row As DataRow
Dim uniqueFileName As String = ""
If Session("ID") Is Nothing Then
lblMessage.Text = "You don't seem to have uploaded any pictures."
Exit Sub
Else
**Dim FileCount As Integer = Request.Form(Request.Form.Count - 2)**
Dim FileName, TargetName As String
Try
Dim Path As String = Server.MapPath(BLL.getAlbumPicUrl(txtStoryTitle.Text.Trim))
If Not IO.Directory.Exists(Path) Then
IO.Directory.CreateDirectory(Path)
End If
Dim StartIndex As Integer
Dim PicCount As Integer
For i As Integer = 0 To Request.Form.Count - 1
If Request.Form(i).ToLower.Contains("jpg") Or Request.Form(i).ToLower.Contains("gif") Or Request.Form(i).ToLower.Contains("png") Then
StartIndex = i + 1
Exit For
End If
Next
For i As Integer = StartIndex To Request.Form.Count - 4 Step 3
FileName = Request.Form(i)
'## If part here is not kaam ka..but still using it for worst case scenario
If IO.File.Exists(Path & FileName) Then
TargetName = Path & FileName
'MsgBox(TargetName & "--- 1")
Dim j As Integer = 1
While IO.File.Exists(TargetName)
TargetName = Path & IO.Path.GetFileNameWithoutExtension(FileName) & "(" & j & ")" & IO.Path.GetExtension(FileName)
j += 1
End While
Else
uniqueFileName = Guid.NewGuid.ToString & "__" & FileName
TargetName = Path & uniqueFileName
End If
IO.File.Move(Server.MapPath("~/TempUploads/" & Session("ID") & "/" & FileName), TargetName)
PicCount += 1
Row = dt.NewRow()
Row(1) = accountId
Row(2) = AlbumID
Row(3) = URL & uniqueFileName
Row(4) = ""
Row(5) = "No Desc"
Row(6) = "False"
Row(7) = ""
Row(8) = "0"
Row(9) = "0"
Row(10) = "True"
dt.Rows.Add(Row)
Next
If BLL.insertImagesIntoAlbum(dt) Then
lblMessage.Text = PicCount & IIf(PicCount = 1, " Picture", " Pictures") & " Saved!"
lblMessage.ForeColor = Drawing.Color.Black
Dim db As SqlDatabase = Connection.connection
Using cmd As DbCommand = db.GetSqlStringCommand("SELECT PictureID,URL FROM AlbumPictures WHERE AlbumID=#AlbumID AND AccountID=#AccountID")
db.AddInParameter(cmd, "AlbumID", Data.DbType.Int32, AlbumID)
db.AddInParameter(cmd, "AccountID", Data.DbType.Int32, accountId)
Using ds As DataSet = db.ExecuteDataSet(cmd)
If ds.Tables(0).Rows.Count > 0 Then
ListView1.DataSource = ds.Tables(0)
ListView1.DataBind()
Else
lblMessage.Text = "No Such Album Exists."
End If
End Using
End Using
'WebNavigator.GoToResponseRedirect(WebNavigator.URLFor.ReturnUrl("~/Memories/SortImages.aspx?id=" & AlbumID))
Else
'TODO:we'll show some error msg
End If
Catch ex As Exception
MsgBox(ex.Message)
lblMessage.Text = "Oo Poop!!"
End Try
End If
Else
WebNavigator.GoToResponseRedirect(WebNavigator.URLFor.LoginWithReturnUrl("~/Memories/CreateAlbum.aspx"))
Exit Sub
End If
End Sub
The above code works fine.I have added an Update Panel in the page to avoid post back, But when i add the button click as a trigger
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSubmit" />
</Triggers>
in the update panel to avoid post back, i get the following error.This happens when i add the button click as a Trigger to the update panel.
The Request.Form returns a NameValueCollection which is accessible by the name of the key or the int indexer. It always returns a String and not an Integer.
Dim FileCount As String = Request.Form(Request.Form.Count - 2)
This is all intuition from the exception message, but on the line
FileCount As Integer = Request.Form(Request.Form.Count - 2)
It looks like Request.Form(Request.Form.Count - 2) is a string, and you're trying trying to assign a it to an integer type.
I don't know what you're trying to do, but the string looks like it contains "true" do you want the following?
FileCount As Integer += Boolean.Parse(Request.Form(Request.Form.Count - 2)) ? 1 : 0;

Resources