I have DataTable that was loaded with a SqlDataReader query. After my DataTable is loaded, I do looping that I was insert data with a SqlCommand every index. But the DataTable is not refreshed. How to refresh the DataTable while data is updated in the database?
connectionx()
Dim dtreader As SqlDataReader
Dim cmddt As New SqlCommand("SELECT * from sometable", con)
dtreader = cmddt.ExecuteReader()
Dim dt As New System.Data.DataTable()
dt.Load(dtreader) 'Here from datareader
For index As Integer = currentRow To dt.Rows.Count - 1
Dim drR As DataRow = dt.NewRow()
Dim reader1 As SqlDataReader
Dim EP As DateTime
Dim EndW As String = dtnow.ToString("MM/dd/yyyy HH:mm")
Dim setEndWaiting As Integer = Convert.ToInt32(adapterSch.SetEndWTime(EndW, Convert.ToInt32(Session("ShipLoadingOrderFK"))))
Dim startPre As DateTime = EndW
Dim endPre As DateTime = startPre + TimeSpan.Parse(defPre)
Dim setPreDocumentTime As Integer = Convert.ToInt32(adapterSch.SetPreDocumentTime(startPre, endPre, Convert.ToInt32(Session("ShipLoadingOrderFK"))))
Dim startPump As DateTime = endPre
Dim endPump As DateTime
Dim shipKey As String = Shipid.SelectedValue
pumpigResult(MinutePumpResult, HoursPumpResult, FlowrateValue, Shipid.SelectedValue, Loading_No.Value, typeLoading.SelectedValue)
If FlowrateValue = 0 Or FlowrateValue = "" Then
endPump = endPre + TimeSpan.Parse(defPumping)
Else
endPump = endPre + New TimeSpan(HoursPumpResult, MinutePumpResult, 0)
End If
Dim setPumpTime As Integer = Convert.ToInt32(adapterSch.SetPumpingTime(startPump, endPump, Convert.ToInt32(Session("ShipLoadingOrderFK"))))
Dim startPost As DateTime = endPump
Dim endPost As DateTime = endPump + TimeSpan.Parse(defPost)
Dim setPostTime As Integer = Convert.ToInt32(adapterSch.SetPostTime(startPost, endPost, Convert.ToInt32(Session("ShipLoadingOrderFK"))))
After insert data while every index with code above. I have get the value on previous row (index-1), but I get the OLD Data before updated.
Dim EP as datetime = Convert.ToDateTime(dt.Rows(index - 1)("PostDocEnd").ToString())
How to refresh the DataTable so that I can get the previous data that has been updated? I have try to re-load DataTable again, but is nothing.
Thank you
Solved!
I just line code for reload datareader at starting index looping and refresh the datatable.
dt.reset()
dtreader = cmddt.ExecuteReader()
Dim dt As New System.Data.DataTable()
dt.Load(dtreader)
It will be reload the datatable while database is changed.
Related
I previously used datagridview but now changed it to use a datatable
`
private void table()
{
//create a data set
DataSet ds = new DataSet();
//create a data table for the data set
DataTable dt = new DataTable();
//create some columns for the datatable
DataColumn dc = new DataColumn("Name");
DataColumn dc2 = new DataColumn("Entry");
DataColumn dc3 = new DataColumn("SL");
DataColumn dc4 = new DataColumn("SL%");
DataColumn dc5 = new DataColumn("TP");
DataColumn dc6 = new DataColumn("TP%");
DataColumn dc7 = new DataColumn("Position");
DataColumn dc8 = new DataColumn("Day");
DataColumn dc9 = new DataColumn("Notes");
//add the columns to the datatable
dt.Columns.Add(dc);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
dt.Columns.Add(dc5);
dt.Columns.Add(dc6);
dt.Columns.Add(dc7);
dt.Columns.Add(dc8);
dt.Columns.Add(dc9);
//add the datatable to the datasource
ds.Tables.Add(dt);
//make this data the datasource of our gridview
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.AutoSize = true;
}
`
When using datagridview i used this code on a button click event to add a row
dataGridView1.Rows.Add(name, EntryPrice.Text, StopPrice.Text, slper, ProfitPrice.Text, tpper, pos, day, NotesTB.Text);
How do I add a row to the datatable with the same values using a button click event?
Using
dt.Rows.Add
isnt recognising the dt within my button click
Found an answer from another user
var devents = (DataTable)dataGridView3.DataSource;
DataRow newRow = devents.NewRow();
newRow["start_time"] = new_starttime;
newRow["stop_time"] = new_stoptime;
newRow["cycle_time"] = new_cycletime;
devents.Rows.Add(newRow);
Credit to #kekusemau
Hope this link helps you:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim table As DataTable = EEDataDataSet.Tables("Users")
' Use the NewRow method to create a DataRow
'with the table's schema.
Dim newuserrow As DataRow = table.NewRow()
' Set values in the columns:
newuserrow("Username") = Me.UsernameTextBox.Text
newuserrow("Password") = Me.PasswordTextBox.Text
' Add the row to the rows collection.
table.Rows.Add(newuserrow)
yourTableAdapter.updateAll(EEDataDataSet)
MsgBox("New User addition successful.")
Me.Close()
End Sub
https://social.msdn.microsoft.com/Forums/vstudio/en-US/eddc0789-67f8-46ff-a35a-01d67a5e4944/add-a-row-to-a-datatable-from-a-form-button-click?forum=vbgeneral
I have 2 different databases - SQLite and PostgreSQL and i trying to make tiny math on table from this databases.
Both tables contains columns nr_serii and ilosc, SQLite:
And Postgres:
I established a connection to both databases and populate dataset. Maybe i should use different place to store the data?
I need to substraction column ilosc: (sqlite-postgres), but not know how to do that.
For example, for each nr_serii make substraction column ilosc:
nr_serii:222222
ilosc:15-7=8
Finally i want to show output data to datagridview.
When i use messagebox i can see the data in dataset. Here is my part of code:
string cs = #"URI = file:" + Sdatabase;
string csP = conParam;
string sqlP = "select nr_serii, ilosc from stany";
string sql = "select nr_serii, ilosc from przychod";
using var con = new SQLiteConnection(cs);
con.Open();
using var cmd = new SQLiteCommand(sql, con);
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
using var conP = new NpgsqlConnection(csP);
conP.Open();
NpgsqlCommand cmdP = new NpgsqlCommand(sqlP, conP);
NpgsqlDataAdapter DA = new NpgsqlDataAdapter(cmdP);
DataSet dsP = new DataSet();
DA.Fill(dsP);
//----------test-----------
foreach (DataRow row in dsP.Tables[0].Rows)
{
var nr_serii = row["nr_serii"];
var ilosc = row["ilosc"];
MessageBox.Show(nr_serii +","+ ilosc);
}
//--------------------------
For example, you can browse data table from first datasource ds and search for a matching row by value of nr_serii column for each row in the datatable in second datasource dsP, and if found, add a new row with the calculation result to the new third result table.
Then you don't forget to solve the problem of what to do with records that are only in the first ds or only in the second dsP datasource, depending on the value of the nr_serii column.
Program code example:
//prepare result third DataTable
DataTable resultDt = new DataTable();
resultDt.Columns.Add("nr_serii");
resultDt.Columns.Add("ilosc");
//add content to result DataTable
foreach (DataRow row in ds.Tables[0].Rows)
{
var nr_serii = row["nr_serii"];
var ilosc = row["ilosc"];
DataRow drP = null;
foreach (DataRow dataRow in dsP.Tables[0].Rows)
{
if (nr_serii.ToString() == (string)dataRow["nr_serii"])
{
drP = dataRow;
break;
}
}
if (drP != null)
{
var dr = resultDt.NewRow();
dr["nr_serii"] = nr_serii;
dr["ilosc"] = (int)ilosc - (int)drP["ilosc"];
resultDt.Rows.Add(dr);
}
}
i created datatables by code and i added those tables to data set . they working fine .but when i pass this dataset to my report i get nothing .here my codes
Dim dt As DataTable = New DAL().selectdatatable(String.Format("SELECT PT.PT_Code, PT.age_sex2, PT.fullname2, Ptsense.PT_Date, DR.Dr_Name, Ptsense.sample, Ptsense.G, Ptsense.coun, Ptsense.comm, Ptsense.organism, Ptsense.lowsens FROM (PT INNER JOIN Ptsense ON PT.PT_Code = Ptsense.PT_Code) INNER JOIN DR ON PT.DR_Code = DR.Dr_Code WHERE PT.PT_Code={0} AND Ptsense.PT_Date=#{1}# AND Ptsense.lowsens <>'{2}'", Txtcode.Text, DateTimePicker1.Value.ToString("dd/MM/yyyy"), ""))
Dim dt3 As DataTable = New DAL().selectdatatable(String.Format("SELECT labdetails.labnme, labdetails.labspecial, labdetails.labadress, labdetails.labphone, labdetails.labtime, labdetails.lablogo,labdetails.labnameenglish,labdetails.labspecialenglish FROM labdetails;"))
Dim dt4 As DataTable = New DAL().selectdatatable(String.Format("SELECT PT.PT_Code, PT.age_sex2, PT.fullname2, Ptsense.PT_Date, DR.Dr_Name, Ptsense.sample, Ptsense.G, Ptsense.coun, Ptsense.comm, Ptsense.organism, Ptsense.lowsens, Ptsense.resis FROM (PT INNER JOIN Ptsense ON PT.PT_Code = Ptsense.PT_Code) INNER JOIN DR ON PT.DR_Code = DR.Dr_Code WHERE PT.PT_Code={0} AND Ptsense.PT_Date=#{1}# AND Ptsense.resis <>'{2}'", Txtcode.Text, DateTimePicker1.Value.ToString("dd/MM/yyyy"), ""))
Dim ds As New DataSet
ds.Tables.AddRange({dt, dt3, dt4})
rprt.SetDataSource(ds)
I have created a webform which imports the excel file into gridview.
Now I want to add checkbox control to each header (along with the header text).
Below is the code where I am
1. Importing the excel data.
2. Store it into a datatable
3. Creating gridview dynamically
4. Binding the data into the gridview.
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
If FileUpload1.HasFile Then
Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
Dim FolderPath As String = ConfigurationManager.AppSettings("FolderPath")
Dim FilePath As String = Server.MapPath(FolderPath + FileName)
FileUpload1.SaveAs(FilePath)
Import_To_Grid(FilePath, Extension, rbHDR.SelectedItem.Text)
End If
End Sub
Private Sub Import_To_Grid(ByVal FilePath As String, ByVal Extension As String, ByVal isHDR As String)
Dim conStr As String = ""
Select Case Extension
Case ".xls"
conStr = ConfigurationManager.ConnectionStrings("Excel03ConString").ConnectionString
Exit Select
Case ".xlsx"
conStr = ConfigurationManager.ConnectionStrings("Excel07ConString").ConnectionString
Exit Select
End Select
conStr = String.Format(conStr, FilePath, isHDR)
Dim connExcel As New OleDbConnection(conStr)
Dim cmdExcel As New OleDbCommand()
Dim oda As New OleDbDataAdapter()
Dim dt As New DataTable()
cmdExcel.Connection = connExcel
connExcel.Open()
Dim dtExcelSchema As DataTable
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim SheetName As String = dtExcelSchema.Rows(0)("TABLE_NAME").ToString()
connExcel.Close()
connExcel.Open()
cmdExcel.CommandText = "SELECT * From [" & SheetName & "]"
oda.SelectCommand = cmdExcel
oda.Fill(dt)
connExcel.Close()
Dim GridView1 As GridView = New GridView
GridView1.AutoGenerateColumns = False
For i As Integer = 0 To dt.Columns.Count - 1
Dim boundfield As BoundField = New BoundField
boundfield.DataField = dt.Columns(i).ColumnName.ToString()
boundfield.HeaderText = dt.Columns(i).ColumnName.ToString()
GridView1.Columns.Add(boundfield)
Next
GridView1.DataSource = dt
GridView1.DataBind()
Panel1.Controls.Add(GridView1)
End Sub
All working fine. But when it comes to adding checkbox to header text, I am completely blank. Kindly suggest the solution or any other approach I can use.
No Comments :(
Anyway, I have done it myself. It was pretty simple. I was thinking too much. Here's the code.
ASPX:
<form id="form1" runat="server">
<div>
Import Excel File:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
OnClick="btnUpload_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Has Header ?" />
<asp:RadioButtonList ID="rbHDR" runat="server">
<asp:ListItem Text = "Yes" Value = "Yes" Selected = "True" >
</asp:ListItem>
<asp:ListItem Text = "No" Value = "No"></asp:ListItem>
</asp:RadioButtonList>
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>
</form>
Codebehind:
Private Sub Import_To_Grid(ByVal FilePath As String, ByVal Extension As String, ByVal isHDR As String)
Dim conStr As String = ""
Select Case Extension
Case ".xls"
'Excel 97-03
conStr = ConfigurationManager.ConnectionStrings("Excel03ConString") _
.ConnectionString
Exit Select
Case ".xlsx"
'Excel 07
conStr = ConfigurationManager.ConnectionStrings("Excel07ConString") _
.ConnectionString
Exit Select
End Select
conStr = String.Format(conStr, FilePath, isHDR)
Dim connExcel As New OleDbConnection(conStr)
Dim cmdExcel As New OleDbCommand()
Dim oda As New OleDbDataAdapter()
Dim dt As New DataTable()
cmdExcel.Connection = connExcel
connExcel.Open()
Dim dtExcelSchema As DataTable
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim SheetName As String = dtExcelSchema.Rows(0)("TABLE_NAME").ToString()
connExcel.Close()
connExcel.Open()
cmdExcel.CommandText = "SELECT * From [" & SheetName & "]"
oda.SelectCommand = cmdExcel
oda.Fill(dt)
connExcel.Close()
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
Protected Sub GridView1_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowCreated
' Check the header type
If e.Row.RowType = DataControlRowType.Header Then
Dim litHeader As Literal
Dim txtSearch As CheckBox
' loop through each cell
For i As Integer = 0 To (e.Row.Cells.Count - 1)
litHeader = New Literal
txtSearch = New CheckBox
' get the current header text
litHeader.Text = e.Row.Cells(i).Text & " "
' add the header text plus a new textbox
e.Row.Cells(i).Controls.Add(txtSearch)
e.Row.Cells(i).Controls.Add(litHeader)
Next
End If
End Sub
What is the fastest way to convert anonymous type to DataTable?
Update:
I want to get and populate DataTable from anonymous type. If reflection is neccesary, how can I to do it using reflection?
Found here:
var result = from p in dataSource
group p by p.City into cities
select new { Property1 = cities.Key, Property 2= cities.Average(p => p.Age) };
dt.Columns.Add("Property1");
dt.Columns.Add("Property2");
foreach (var item in result)
{
dt.Rows.Add(item.Property1,item.Property2);
}
See here for a generic solution: Convert generic List/Enumerable to DataTable?
///fill dt1
Dim dt1 As New DataTable dt1 = connection.LoadPoliceData("")
///fll dt2
Dim dt2 As New DataTable dt2 = connection.LoadDataCompare("")
////fill enumerable data(anonymous data) in dt , using linq query
Dim dt As New DataTable
dt.Columns.Add("Name", GetType(String))
dt.Columns.Add("Mobile", GetType(String))
Dim data1 = (From datarow1 In dt1.AsEnumerable Join datarow2 In dt2.AsEnumerable
On datarow1.Field(Of String)("NameofPerson") Equals datarow2.Field(Of String)("Name") And datarow1.Field(Of String)("Mobile") Equals datarow2.Field(Of String)("MobileNumber")
Select dt.LoadDataRow(New Object() {datarow1.Field(Of String)("NameofPerson"), datarow2.Field(Of String)("MobileNumber")}, False)).Distinct().ToList()
Dim i = dt.Rows.Count
record in dt(datatable variable )
///summary fill datatable one (dt1)
Dim dt1 As New DataTable
dt1 = connection.LoadPoliceData("")
///summary fill datatable one (dt2)
Dim dt2 As New DataTable
dt2 = connection.LoadDataCompare("")
/// summary declare datatable save . where i want fill Enumerable data
Dim save As New DataTable
save.Columns.Add("Name", GetType(String))
save.Columns.Add("Mobile", GetType(String))
///summary writing linq query with join of dt1 and dt2 , And datatable(save)
Dim data1 = (From datarow1 In dt1.AsEnumerable
Join datarow2 In dt2.AsEnumerable
On datarow1.Field(Of String)("NameofPerson") Equals datarow2.Field(Of String)("Name") And datarow1.Field(Of String)("Mobile") Equals datarow2.Field(Of String)("MobileNumber")
Select save.LoadDataRow(New Object() {datarow1.Field(Of String)("NameofPerson"), datarow2.Field(Of String)("MobileNumber")}, False)).Distinct().ToList()
///summary count of datatable save
Dim i = save.Rows.Count