this is my code. When i do debugging i have problem at line dtnew(0)("PANEL_ID") = a.Trim
and i have no idea how to solve this. i'm very new in vb.net. Would be great to hear opinions from expert. There is certain part of the code i alter and delete. So im sorry if its seems like not a complete code.
Dim dt As New DataTable
Try
*
open connection *
oraComm.CommandText = "SELECT Panel_ID, CELL_TYPE, IV_RESULT, MODEL_CD,IV_MODE,modelname,stringlength, quantitycell, " & _ " A_CL_LT_A1, A_CL_LT_A2, A_CL_LT_B1, A_CL_LT_B2, " & _ " A_WAF_ID_1, A_WAF_ID_2, A_WAF_ID_3, A_WAF_ID_4, " & _ " B_CL_LT_A1, B_CL_LT_A2, B_CL_LT_B1, B_CL_LT_B2, " & _ " B_WAF_ID_1, B_WAF_ID_2, B_WAF_ID_3, B_WAF_ID_4, " & _ " C_CL_LT_A1, C_CL_LT_A2, C_CL_LT_B1, C_CL_LT_B2, " & _ " C_WAF_ID_1, C_WAF_ID_2, C_WAF_ID_3, C_WAF_ID_4 " & _
"FROM table1 s,table2 m " & _
"WHERE s.areacode ='hawaii' AND m.areacode ='hawaii' AND s.panel_id = '" & Me.TextBox1.Text.Trim & "' "
ada = New Oracle.DataAccess.Client.OracleDataAdapter(oraComm)
ada.Fill(ds.Tables("M_DATANEW"))
dt = ds.Tables("M_DATANEW")
Dim a, c, d, e, f As String
Dim dtnew = New DataTable()
dtnew.Columns.Add("PANEL_ID", GetType(String))
dtnew.Columns.Add("CELL_TYPE", GetType(String))
dtnew.Columns.Add("IV_RESULT", GetType(String))
dtnew.Columns.Add("IV_MODE", GetType(String))
dtnew.Columns.Add("MODEL_CD", GetType(String))
a = dt.Rows(0)("panel_id").ToString.Trim
c = dt.Rows(0)("cell_type").ToString.Trim
d = dt.Rows(0)("iv_result").ToString.Trim
e = dt.Rows(0)("iv_mode").ToString.Trim
f = dt.Rows(0)("model_cd").ToString.Trim
Dim waf_ini As String = ""
For w = 1 To CInt(dt.Rows(0)("stringlength")) + 1
For x = 1 To CInt(dt.Rows(0)("cellquantity")) + 1
If w = 1 Then
waf_ini = "A_WAF_ID"
ElseIf w = 2 Then
waf_ini = "B_WAF_ID"
ElseIf w = 3 Then
waf_ini = "C_WAF_ID"
End If
dtnew.NewRow()
dtnew(0)("PANEL_ID") = a.Trim
dtnew(0)("CELL_TYPE") = c.Trim
dtnew(0)("IV_RESULT") = d.Trim
dtnew(0)("IV_MODE") = e.Trim
dtnew(0)("MODEL_CD") = f.Trim
dtnew.Rows.Add()
Next
Next
If dt.Rows.Count < > 0 Then
GridView1.DataSource = dt
GridView1.DataBind()
Else
GridView1.DataSource = Nothing
GridView1.DataBind()
End If
Catch ex As Exception
Throw ex
Finally
*
close connection *
End Try
End Sub
You have to create a new row before populating it.
dtnew.Rows.Add(dtnew.NewRow)
a = dtnew.Rows(0)("panel_id").ToString.Trim
c = dtnew.Rows(0)("cell_type").ToString.Trim
d = dtnew.Rows(0)("iv_result").ToString.Trim
e = dtnew.Rows(0)("iv_mode").ToString.Trim
f = dtnew.Rows(0)("model_cd").ToString.Trim
Related
I have the following VB.net code that updates the row from Boundedfields using the identifying the cell number.
Protected Sub grvPos_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles grvPos.RowUpdating
Dim cs As String
Dim con As iDB2Connection
Dim sql As String
Dim cmd As iDB2Command
Dim valDate As Integer
Dim portCode As String
Dim secCode As String
Dim valType As String
Dim portName As String
Dim ISINno As String
Dim secName As String
Dim secCcyAbbr As String
Dim trxBccy As Decimal
Dim quantity As Integer
Dim mktPrice As Integer
Dim avgCost As Integer
Dim avgBvalSc As Integer
Dim avgBvalBc As Integer
Dim intAmtSc As Integer
Dim intAmtBc As Integer
Dim gr As GridViewRow
gr = grvPos.Rows(e.RowIndex)
valDate = grvPos.DataKeys(gr.RowIndex).Values("VALN_DATE")
portCode = grvPos.DataKeys(gr.RowIndex).Values("PORT_CODE").ToString()
secCode = grvPos.DataKeys(gr.RowIndex).Values("SEC_CODE").ToString()
valType = grvPos.Rows(gr.RowIndex).Cells(2).ToString()
portName = grvPos.Rows(gr.RowIndex).Cells(4).ToString()
ISINno = grvPos.Rows(gr.RowIndex).Cells(6).ToString()
secName = grvPos.Rows(gr.RowIndex).Cells(7).ToString()
secCcyAbbr = grvPos.Rows(gr.RowIndex).Cells(8).ToString()
trxBccy = grvPos.Rows(gr.RowIndex).Cells(9).ToString()
quantity = CInt(grvPos.Rows(gr.RowIndex).Cells(10).ToString())
mktPrice = CInt(grvPos.Rows(gr.RowIndex).Cells(11).ToString())
avgCost = CInt(grvPos.Rows(gr.RowIndex).Cells(14).ToString())
avgBvalSc = CInt(grvPos.Rows(gr.RowIndex).Cells(15).ToString())
avgBvalBc = CInt(grvPos.Rows(gr.RowIndex).Cells(16).ToString())
intAmtSc = CInt(grvPos.Rows(gr.RowIndex).Cells(17).ToString())
intAmtBc = CInt(grvPos.Rows(gr.RowIndex).Cells(18).ToString())
cs = ConfigurationManager.ConnectionStrings("ConnectionStringDB2").ConnectionString
con = New iDB2Connection(cs)
sql = "MERGE INTO GICPFDTA.OPTR_POS_FIX O " &
"USING OLYFPRO.FDBVAL F ON O.SEC_CODE = F.VLVALR " &
"AND (O.VALN_DATE = #VALN_DATE) " &
"AND (O.PORT_CODE = #PORT_CODE) " &
"AND (O.SEC_CODE = #SEC_CODE) " &
"WHEN MATCHED THEN UPDATE SET " &
"O.VAL_TYPE = #VAL_TYPE " &
",O.PORT_SNAME = #PORT_SNAME " &
",O.ISIN_NO = #ISIN_NO " &
",O.SEC_SNAME = #SEC_SNAME " &
",O.SEC_CCY_ABBR = #SEC_CCY_ABBR " &
",O.TRX_BCCY_EX_RATE = #TRX_BCCY_EX_RATE " &
",O.QUANTITY = #QUANTITY " &
",O.MKT_PRICE = #MKT_PRICE " &
",O.AVG_COST = #AVG_COST " &
",O.AVG_BVAL_SC = #AVG_BVAL_SC " &
",O.AVG_BVAL_BC = #AVG_BVAL_BC " &
",O.INT_AMT_SC = #INT_AMT_SC " &
",O.INT_AMT_BC = #INT_AMT_BC " &
",O.MVAL_AMT_SC = ROUND(#QUANTITY * #MKT_PRICE / (" &
"CASE " &
"WHEN F.VLGTI = 100 " &
"THEN 100 " &
"ELSE 1 " &
"END" &
"), 3) " &
",O.MVAL_AMT_BC = ROUND(#QUANTITY * #MKT_PRICE / (" &
"CASE " &
"WHEN F.VLGTI = 100 " &
"THEN 100 " &
"ELSE 1 " &
"END" &
") / #TRX_BCCY_EX_RATE, 3)"
cmd = New iDB2Command(sql, con)
cmd.Parameters.AddWithValue("#VALN_DATE", valDate)
cmd.Parameters.AddWithValue("#PORT_CODE", portCode)
cmd.Parameters.AddWithValue("#SEC_CODE", secCode)
cmd.Parameters.AddWithValue("#VAL_TYPE", valType)
cmd.Parameters.AddWithValue("#PORT_SNAME", portName)
cmd.Parameters.AddWithValue("#ISIN_NO", ISINno)
cmd.Parameters.AddWithValue("#SEC_SNAME", secName)
cmd.Parameters.AddWithValue("#SEC_CCY_ABBR", secCcyAbbr)
cmd.Parameters.AddWithValue("#TRX_BCCY_EX_RATE", trxBccy)
cmd.Parameters.AddWithValue("#TRX_BCCY_EX_RATE", trxBccy)
cmd.Parameters.AddWithValue("#QUANTITY", quantity)
cmd.Parameters.AddWithValue("#QUANTITY", quantity)
cmd.Parameters.AddWithValue("#QUANTITY", quantity)
cmd.Parameters.AddWithValue("#MKT_PRICE", mktPrice)
cmd.Parameters.AddWithValue("#MKT_PRICE", mktPrice)
cmd.Parameters.AddWithValue("#MKT_PRICE", mktPrice)
cmd.Parameters.AddWithValue("#AVG_COST", avgCost)
cmd.Parameters.AddWithValue("#AVG_BVAL_SC", avgBvalSc)
cmd.Parameters.AddWithValue("#AVG_BVAL_BC", avgBvalBc)
cmd.Parameters.AddWithValue("#INT_AMT_SC", intAmtSc)
cmd.Parameters.AddWithValue("#INT_AMT_BC", intAmtBc)
Try
lblError.Text = ""
Using con
con.Open()
cmd.ExecuteNonQuery()
gridLoad()
End Using
Catch ex As Exception
Throw
End Try
End Sub
The trxBccy variable is Numeric data type, but I specified it as Decimal, I also tried Integer data type.
When I try to update a row I get the following error:
Conversion from string "System.Web.UI.WebControls.DataCo" to type 'Decimal' is not valid.
I appreciate any help.
Thanks in advance
I was able to capture the values from the bounded fields using the below code.
Protected Sub grvPos_RowUpdating(sender As Object, e As GridViewUpdateEventArgs) Handles grvPos.RowUpdating
Dim cs As String
Dim con As iDB2Connection
Dim sql As String
Dim cmd As iDB2Command
Dim valDate As Integer
Dim portCode As String
Dim secCode As String
Dim valType As String
Dim portName As String
Dim ISINno As String
Dim secName As String
Dim secCcyAbbr As String
Dim trxBccy As Decimal
Dim quantity As Decimal
Dim mktPrice As Decimal
Dim avgCost As Decimal
Dim avgBvalSc As Decimal
Dim avgBvalBc As Decimal
Dim intAmtSc As Decimal
Dim intAmtBc As Decimal
Dim gr As GridViewRow
gr = grvPos.Rows(e.RowIndex)
valDate = grvPos.DataKeys(gr.RowIndex).Values("VALN_DATE")
portCode = grvPos.DataKeys(gr.RowIndex).Values("PORT_CODE").ToString()
secCode = grvPos.DataKeys(gr.RowIndex).Values("SEC_CODE").ToString()
valType = e.NewValues("VAL_TYPE").ToString()
portName = e.NewValues("PORT_SNAME").ToString()
ISINno = e.NewValues("ISIN_NO").ToString()
secName = e.NewValues("SEC_SNAME").ToString()
secCcyAbbr = e.NewValues("SEC_CCY_ABBR").ToString()
trxBccy = e.NewValues("TRX_BCCY_EX_RATE").ToString()
quantity = e.NewValues("QUANTITY").ToString()
mktPrice = e.NewValues("MKT_PRICE").ToString()
avgCost = e.NewValues("AVG_COST").ToString()
avgBvalSc = e.NewValues("AVG_BVAL_SC").ToString()
avgBvalBc = e.NewValues("AVG_BVAL_BC").ToString()
intAmtSc = e.NewValues("INT_AMT_SC").ToString()
intAmtBc = e.NewValues("INT_AMT_BC").ToString()
cs = ConfigurationManager.ConnectionStrings("ConnectionStringDB2").ConnectionString
con = New iDB2Connection(cs)
sql = "MERGE INTO GICPFDTA.OPTR_POS_FIX O " &
"USING OLYFPRO.FDBVAL F ON O.SEC_CODE = F.VLVALR " &
"AND (O.VALN_DATE = #VALN_DATE) " &
"AND (O.PORT_CODE = #PORT_CODE) " &
"AND (O.SEC_CODE = #SEC_CODE) " &
"WHEN MATCHED THEN UPDATE SET " &
"O.VAL_TYPE = #VAL_TYPE " &
",O.PORT_SNAME = #PORT_SNAME " &
",O.ISIN_NO = #ISIN_NO " &
",O.SEC_SNAME = #SEC_SNAME " &
",O.SEC_CCY_ABBR = #SEC_CCY_ABBR " &
",O.TRX_BCCY_EX_RATE = #TRX_BCCY_EX_RATE " &
",O.QUANTITY = #QUANTITY " &
",O.MKT_PRICE = #MKT_PRICE " &
",O.AVG_COST = #AVG_COST " &
",O.AVG_BVAL_SC = #AVG_BVAL_SC " &
",O.AVG_BVAL_BC = #AVG_BVAL_BC " &
",O.INT_AMT_SC = #INT_AMT_SC " &
",O.INT_AMT_BC = #INT_AMT_BC " &
",O.MVAL_AMT_SC = ROUND(#QUANTITY * #MKT_PRICE / (" &
"CASE " &
"WHEN F.VLGTI = 100 " &
"THEN 100 " &
"ELSE 1 " &
"END" &
"), 3) " &
",O.MVAL_AMT_BC = ROUND(#QUANTITY * #MKT_PRICE / (" &
"CASE " &
"WHEN F.VLGTI = 100 " &
"THEN 100 " &
"ELSE 1 " &
"END" &
") / #TRX_BCCY_EX_RATE, 3)"
cmd = New iDB2Command(sql, con)
cmd.Parameters.AddWithValue("#VALN_DATE", valDate)
cmd.Parameters.AddWithValue("#PORT_CODE", portCode)
cmd.Parameters.AddWithValue("#SEC_CODE", secCode)
cmd.Parameters.AddWithValue("#VAL_TYPE", valType)
cmd.Parameters.AddWithValue("#PORT_SNAME", portName)
cmd.Parameters.AddWithValue("#ISIN_NO", ISINno)
cmd.Parameters.AddWithValue("#SEC_SNAME", secName)
cmd.Parameters.AddWithValue("#SEC_CCY_ABBR", secCcyAbbr)
cmd.Parameters.AddWithValue("#TRX_BCCY_EX_RATE", trxBccy)
cmd.Parameters.AddWithValue("#TRX_BCCY_EX_RATE", trxBccy)
cmd.Parameters.AddWithValue("#QUANTITY", quantity)
cmd.Parameters.AddWithValue("#QUANTITY", quantity)
cmd.Parameters.AddWithValue("#QUANTITY", quantity)
cmd.Parameters.AddWithValue("#MKT_PRICE", mktPrice)
cmd.Parameters.AddWithValue("#MKT_PRICE", mktPrice)
cmd.Parameters.AddWithValue("#MKT_PRICE", mktPrice)
cmd.Parameters.AddWithValue("#AVG_COST", avgCost)
cmd.Parameters.AddWithValue("#AVG_BVAL_SC", avgBvalSc)
cmd.Parameters.AddWithValue("#AVG_BVAL_BC", avgBvalBc)
cmd.Parameters.AddWithValue("#INT_AMT_SC", intAmtSc)
cmd.Parameters.AddWithValue("#INT_AMT_BC", intAmtBc)
Try
lblError.Text = ""
Using con
con.Open()
cmd.ExecuteNonQuery()
grvPos.EditIndex = -1
gridLoad()
End Using
Catch ex As Exception
Throw
End Try
End Sub
I have two datatables. One datatable that has account and balance and the other datatable has the fee and the balance. For example:
Datatable 1
111111 35.00
111112 50.00
Datatable 2
111111sf 5.00
111112sf 8.00
New datatable should show the account from datatable 1 and the total balance(datatable 1 and datatable 2)
111111 40.00
111112 58.00
how can I compare the two datatables to go through each row and add these values and then create a new datatable? I did it with three gridviews and List(Of string) but it was dirty. I would appreciate any help.
Here is my code:
sqladapter = New SqlDataAdapter("SELECt account, balance FROM DEBT WHERE (account = #account)", conn)
sqladapter = New SqlDataAdapter("SELECt account, balance FROM DEBT WHERE (account = #account)", conn)
Dim ds As New DataSet()
sqladapter.SelectCommand.Parameters.AddWithValue("#account", 111111)
sqladapter2.SelectCommand.Parameters.AddWithValue("#account", 111111)
sqladapter.Fill(ds, "WithSFDT")
sqladapter2.Fill(ds, "WithoutSFDT")
'get datatable
Dim dtWith As DataTable = ds.Tables("WithSFDT")
Dim dtWithout As DataTable = ds.Tables("WithoutSFDT")
Here is the dirty code in gridview:
Dim itemlist As New List(Of String)
For Each row1 As GridViewRow In GridView1.Rows
If row1.RowType = DataControlRowType.DataRow Then
Dim gv1Value As String = row1.Cells(1).Text
Dim gv1col3 As Decimal = row1.Cells(2).Text
Dim lname As String = row1.Cells(3).Text
Dim fname As String = row1.Cells(4).Text
Dim TOdate As DateTime = row1.Cells(5).Text
Dim debtnum As Integer = row1.Cells(6).Text
For Each row2 As GridViewRow In GridView2.Rows
If row2.RowType = DataControlRowType.DataRow Then
Dim gv2Value As String = row2.Cells(3).Text
Dim gv2col3 As Decimal = row2.Cells(1).Text
If gv1Value.Contains(gv2Value) Then
GridView1.Visible = False
GridView2.Visible = False
GridView3.Visible = True
itemlist.Add(TOdate & " | " & gv1Value & " | " & fname & " " & lname & " " & " | " & gv1col3 + gv2col3 & " " & " | " & debtnum)
ElseIf gv2Value Is Nothing Then
GridView3.Visible = False
GridView1.Visible = True
'itemlist.Add(gv1col3 + gv2col3)
'list2.Add(gv1Value)
End If
End If
Next
End If
Next
If itemlist.Count > 0 Then
GridView3.DataSource = itemlist
GridView3.DataBind()
GridView3.HeaderRow.Cells(0).Text = "T/O Date" & " | " & " Account" & " | " & " Name" & " | " & "Balance" & " | " & "Debt #"
' GridView3.HeaderRow.Cells(1).Text = " Balance"
'GridView4.Columns.Add(
GridView3.Visible = True
End If
The problem with is is that the Gridview3 shows the itemlist in one row and it doesn't look like a table.
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
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
This is a sample of my code. I am using Microsoft Visual Studio 2010, with asp.net version 2.0, when the user clicks the import button, the csv file will be saved in the database. My code contains errors, and I do not know how to solve them, please help!
protected void btnImport_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection (#"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
StreamReader Sr = new StreamReader("filepath");
string line;
while ((line = Sr.ReadLine()) != null)
{
line = Sr.ReadLine();
}
const string SQL = "INSERT INTO [Guest] ([GuestName], [IC_Number], [EventName], [GuestID]) VALUES (#GuestName, #IC_Number, #EventName, #GuestID)";
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.Parameters.AddWithValue("#GuestName", Sr);
cmd.Parameters.AddWithValue("#IC_Number", Sr);
cmd.Parameters.AddWithValue("#EventName", Sr);
cmd.Parameters.AddWithValue("#GuestID", Sr);
con.Open();
cmd.ExecuteNonQuery();// 1,0 will determine whether line is inserted, upload has error...
con.Close();
}
Your insert query must be in your while
Sr is not your parameter, but line which contains an array of your data. So it is probably line[i] that you must give to AddWithValue
You are assigning line = Sr.ReadLine() twice in your code, just do it in the while
So try something like this:
protected void btnImport_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection (#"Data Source=localhost\SQLEXPRESS;Initial Catalog=PSeminar;Integrated Security=true;Trusted_Connection=Yes;MultipleActiveResultSets=true");
con.Open();
StreamReader Sr = new StreamReader("filepath");
string line;
string SQL = "INSERT INTO [Guest] ([GuestName], [IC_Number], [EventName], [GuestID]) VALUES (#GuestName, #IC_Number, #EventName, #GuestID)";
while ((line = Sr.ReadLine()) != null)
{
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.Parameters.AddWithValue("#GuestName", line[0]);
cmd.Parameters.AddWithValue("#IC_Number", line[1]);
cmd.Parameters.AddWithValue("#EventName", line[2]);
cmd.Parameters.AddWithValue("#GuestID", line[3]);
cmd.ExecuteNonQuery();// 1,0 will determine whether line is inserted, upload has error...
}
con.Close();
}
i have done something like this however it was xls files i needed to import but not much differentce really, here is the code i used
Protected Sub ButtonImport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButtonImport.Click
PanelView.Visible = False
PanelUpload.Visible = False
PanelImport.Visible = True
LabelImport.Text = "" 'reset to blank
Dim xConnstr As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & (Server.MapPath("SiteTemplate.xls")) & ";" & _
"Extended Properties=Excel 8.0"
' create your excel connection object using the connection string
Dim objXConn As New System.Data.OleDb.OleDbConnection(xConnstr)
objXConn.Open()
Dim objCommand As New OleDbCommand("SELECT * FROM [importsites$]", objXConn)
'Creating the data reader
Dim reader As OleDbDataReader
reader = objCommand.ExecuteReader()
Dim counter As Integer = 0
While reader.Read()
counter = counter + 1
Dim siteID As Integer = 0
Dim siteIWSref As String = Convert.ToString(reader("siteIWSref"))
If siteIWSref = "" Then
siteIWSref = "."
End If
Dim siteUPRN As String = Convert.ToString(reader("siteUPRN"))
If siteUPRN = "" Then
siteUPRN = "."
End If
Dim siteName As String = Convert.ToString(reader("siteName"))
Dim siteAdd1 As String = Convert.ToString(reader("siteAdd1"))
Dim siteAdd2 As String = Convert.ToString(reader("siteAdd2"))
Dim siteAdd3 As String = Convert.ToString(reader("siteAdd3"))
Dim sitePcode As String = Convert.ToString(reader("sitePcode"))
Dim siteContact As String = Convert.ToString(reader("siteContact"))
Dim siteContactPos As String = Convert.ToString(reader("siteContactPos"))
Dim siteContactTel As String = Convert.ToString(reader("siteContactTel"))
Dim siteDesc As String = Convert.ToString(reader("siteDesc"))
Dim siteCompany As Integer = CInt(CompanyDD.SelectedValue)
Dim siteOccupants As String = Convert.ToString(reader("siteOccupants"))
Dim siteType As String = Convert.ToString(reader("siteType"))
siteID = ImportIntotblSite(siteIWSref, siteUPRN, siteName, siteAdd1, siteAdd2, siteAdd3, sitePcode, siteContact, siteContactPos, siteContactTel, siteDesc, siteCompany, siteOccupants, siteType)
LabelImport.Text &= siteID & siteIWSref & " " & siteUPRN & " " & siteName & " " & siteAdd1 & " " & siteAdd2 & " " & siteAdd3 & " " & " " & sitePcode & " " & siteContact & " " & siteContactPos & " " & siteContactTel & " " & siteDesc & " " & siteCompany & " " & siteOccupants & " " & " " & siteType & "<br>"
End While
reader.Close()
objCommand.Dispose()
objXConn.Close()
btnBack.Enabled = True
btnBack.Visible = True
btnSave.Visible = True
btnSave.Enabled = True
End Sub
Protected Function ImportIntotblSite(ByVal siteIWSref As String, ByVal siteUPRN As String, ByVal siteName As String, ByVal siteAdd1 As String, ByVal siteAdd2 As String, ByVal siteAdd3 As String, ByVal sitePcode As String, ByVal siteContact As String, ByVal siteContactPos As String, ByVal siteContactTel As String, ByVal siteDesc As String, ByVal siteCompany As Integer, ByVal siteOccupants As String, ByVal siteType As String) As Integer
siteIWSref = Left(siteIWSref, 20)
siteUPRN = Left(siteUPRN, 20)
siteName = Left(siteName, 60)
siteAdd1 = Left(siteAdd1, 50)
siteAdd2 = Left(siteAdd2, 50)
siteAdd3 = Left(siteAdd3, 50)
sitePcode = Left(sitePcode, 10)
siteContact = Left(siteContact, 35)
siteContactPos = Left(siteContactPos, 35)
siteContactTel = Left(siteContactTel, 20)
siteDesc = Left(siteDesc, 220)
siteOccupants = Left(siteOccupants, 120)
siteType = Left(siteType, 35)
Dim siteID As Integer = 0
Try
Dim SSAdapter As New importSitesDataSetTableAdapters.tblSiteTableAdapter
Dim SSDataTable As importSitesDataSet.tblSiteDataTable = Nothing
SSDataTable = SSAdapter.GetDataByNumbers(siteIWSref, siteName, siteCompany)
If siteName = "" Then
siteName = ""
End If
'see if the category already exists in the table, if not insert it
If Not SSDataTable Is Nothing Then
If siteName = "" Then
LabelImport.Text = LabelImport.Text & _
"<font color=red>ERROR: BLANK SITE NAME: ROW NOT IMPORTED : " & _
"ID: " & siteID & _
" Name: " & siteName & " " & siteCompany & ".</font><br>"
ElseIf SSDataTable.Rows.Count > 0 Then
If Not SSDataTable(0).siteID = Nothing Then
siteID = SSDataTable(0).siteID
LabelImport.Text = LabelImport.Text & _
"<font color=blue> Recorded already exists : " & _
"ID: " & siteID & _
"Name: " & siteName & " " & siteCompany & ".</font><br>"
End If
End If
End If
If siteID = 0 And siteName <> "" Then
siteID = Convert.ToInt32(SSAdapter.InsertQuery(siteIWSref, siteUPRN, siteName, siteAdd1, siteAdd2, siteAdd3, sitePcode, siteContact, siteContactPos, siteContactTel, siteDesc, siteCompany, siteOccupants, siteType))
LabelImport.Text = LabelImport.Text & _
"<font color=green> ROW SUCCESSFULLY IMPORTED: " & _
" ID: " & siteID & _
" Name: " & siteName & " " & siteCompany & ".</font><br>"
End If
Return siteID
'SSAdapter.Dispose()
Catch ex As Exception
LabelImport.Text = LabelImport.Text & "<font color=red>" & ex.ToString & ".</font><br>"
Return 0
End Try
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'TableButtons.Visible = False
'FileUploadExcel.Visible = False
'PanelUpload.Visible = False
btnYes.Visible = False
btnNo.Visible = False
btnBack.Enabled = False
btnBack.Visible = False
ButtonView.Enabled = False
ButtonImport.Enabled = False
btnSave.Visible = False
btnSave.Enabled = False
End Sub
try this and let me know how you get on.
there is a brilliant example of how to upload information onto an sql server at:
http://www.shiningstar.net/aspnet_articles/DataSet/DataSetProject.aspx
i am aware its for excel however surely there cant be that much difference.