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.
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 4 Datetimepicker. the 2 datetimepicker is on dateformat(datefrom,dateto) and the other 2 datetimepicker is on Timeformat(timefrom,timeto).
I want to search a table that display only in datagridview that will display only start on Date from and time from to date to and time to... But my code doenst work.
here's my code:
Dim fromto As String = String.Empty
fromto &= "Select * from setplan where endplan >='" & dtimefrom.Text & "'and endplan >='" & dtimeto.Text & "' and [Dateinput] >='" & ddatefrom.Text & "' and [dateinput] <= '" & ddateto.Text & "'"
Dim connection As String = ("provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Administrator\Documents\planning.accdb;Persist Security Info=False;")
Using conn As New OleDb.OleDbConnection(connection)
Using cmd As New OleDb.OleDbCommand(fromto)
With cmd
.Connection = conn
.CommandType = CommandType.Text
.CommandText = fromto
End With
Try
conn.Open()
cmd.ExecuteNonQuery()
Dim da As New OleDb.OleDbDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds)
If ds.Tables.Count > 0 Then
DataGridView1.DataSource = ds.Tables(0)
End If
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using
End Sub
You need formatted string expressions for your date/time values:
fromto &= "Select * from setplan where endplan >= #" & ddateto.Value.ToString("yyyy'/'MM'/'dd") & " " & dtimeto.Value.ToString("HH':'mm") & "# and [dateinput] >= #" & ddatefrom.Value.ToString("yyyy'/'MM'/'dd") & " " & dtimefrom.Value.ToString("HH':'mm") & "#"
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
I want to put dataset inside of the data to same database in the other datatable
here is my code
Dim Conn As SqlConnection = New SqlConnection("server=localhost;database=MSDSS;Integrated Security=True")
Dim urltext = "Select JournalName, IndexDB, Lang, Category From SJournal where JournalName is not null" + " And IndexDB='" & indexdb & "' And Lang='" & lang & "' And [Impact Factor] Between " & ImpactFactorBegin & " And " & ImpactFactorEnd
Dim Ad As SqlDataAdapter = New SqlDataAdapter(urltext, Conn)
Dim D As DataSet = New DataSet()
Ad.Fill(D, "SJ")
D.Tables(0).Columns.Add(New DataColumn("STV"))
Dim journallist() As String = journalname.Split("()")
For i As Integer = 0 To D.Tables(0).Rows.Count - 1 Step 1
D.Tables(0).Rows(i)("STV") = GetSimilarityWith(D.Tables(0).Rows(i).Item(0).ToString, journalname)
Next i
how can I put this data to other database?
have any idea ?
Dim Conn As SqlConnection = New SqlConnection("server=localhost;database=MSDSS;Integrated Security=True")
Dim Conn2 As SqlConnection = New SqlConnection("server=OTHER DB;database=MSDSS;Integrated Security=True")
Dim urltext = "Select JournalName, IndexDB, Lang, Category From SJournal where JournalName is not null" + " And IndexDB='" & indexdb & "' And Lang='" & lang & "' And [Impact Factor] Between " & ImpactFactorBegin & " And " & ImpactFactorEnd
Dim Ad As SqlDataAdapter = New SqlDataAdapter(urltext, Conn)
Dim Ad2 As SqlDataAdapter = New SqlDataAdapter(urltext, Conn2)
Dim D As DataSet = New DataSet()
Ad.Fill(D, "SJ")
D.Tables(0).Columns.Add(New DataColumn("STV"))
Dim journallist() As String = journalname.Split("()")
For i As Integer = 0 To D.Tables(0).Rows.Count - 1 Step 1
D.Tables(0).Rows(i)("STV") = GetSimilarityWith(D.Tables(0).Rows(i).Item(0).ToString, journalname)
Next i
Ad2.Fill(D, "SJ")
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.