Count how many rows are in the dataset then display as text in a textbox? - vb.net

How can I count how many rows are returned by a dataset and then show the total number of rows as textbox.text and read-only so that the user can only see them but not change them?
so far I have this but it dosent return a number and says it cant find table 0:
tbRecordsFound.Text = ds.Tables(0).Rows.Count

Try something like this:
tbRecordsFound.Text = ds.Tables.Cast<DataTable>().Sum(x => x.Rows.Count).ToString()
You can also do it like this:
Dim recordCount as Integer = 0;
For Each table as Datatable in ds.Tables
recordCount += table.Rows.Count
tbRecordsFound.Text = recordCount.ToString()

tbRecordsFound.Text = ds.Tables(0).Rows.Count
The above code will work, however you need to give the table an identifier, such as:
tbRecordsFound.Text = ds.Tables("TableName").Rows.Count
This can be done via creating a DataAdapter and using the "Fill" function to give the table a name. Here is an example where "da" represents the DataAdapter:
da.Fill(ds, "TableName")

For i As Integer = 0 To yourdatagridviewName.Rows.Count() - 1 Step +1
i = +i
TextBox2.Text = i
Next

Related

How can I merge 2 DataView built in 2 different way?

I am not a c# developer and I found myself at work working with a huge C# application...hug..
Now I am trying to populate an existing DataGrid with some more data which has been 'created' in a different way...let me show you what I mean.
This is how the existing DataView is generated:
Dim lDataSet As System.Data.DataSet
Dim lSqlCommand As New System.Data.SqlClient.SqlCommand
Dim lConvert As New PeoplePlanner.Common.Data.Convert
lSqlCommand.CommandType = CommandType.StoredProcedure
lsqlCommand.CommandText = "AccessIntegrationEmployeeInboundSearch"
lDataSet = objDatabase.GetDataSet(lSqlCommand)
If Not IsNothing(lDataSet) Then
objDataView = lDataSet.Tables(0).DefaultView
End If
There is probably be stuff missing in that code but hopefully it is enough to get an overview. It uses Stored Procedure (SP) to get some data from the DB and it returns the result inside 'lDataSet' and then we do 'objDataView = lDataSet.Tables(0).DefaultView'.
Now the new data which I want to 'merge in' it has the same fields but it is not the response of a SP but of an operation I have created which returns back a List of OnBoardingEmployee(let's call it like that) and if I want to correctly show ONLY the data inside that list this is what I do:
Dim lDataView As System.Data.DataView
Dim op = CoreInjector.Inject(Of IGetAllDataHubIncomingMessagesToBeProcess).Execute()
lDataView = Common.Detail.DataGridOperationHelper.ConvertToDataTable(op.OnBoardingEmployee).DefaultView
objDataView = lDataView
Where:
op contains a list of OnBoardingEmployee which has the same fields as the existing table
lDataView basically is the same as objDataView that's why as last step I assign objDataView = lDataView
Now I would basically like to merge, join, add, whatever
The objDataView created for the first table:
objDataView = lDataSet.Tables(0).DefaultView
with the one I have created afterwards:
lDataView = Common.Detail.DataGridOperationHelper.ConvertToDataTable(x.OnBoardingEmployee).DefaultView
How do I do that? :'(
They have the same data structure or better say they use the same view.
Thanks for the help :)
I have got it working :) this is my implementation:
Dim employeeJSONTable As DataTable
Dim employeeExistingTable As DataTable
Dim myDataRow As DataRow
Dim employeeID As Integer
if Request.QueryString.Get("Function") = "HubInbound" then
Dim employeeJSONList = CoreInjector.Inject(Of IGetAllDataHubIncomingMessagesToBeProcess).Execute()
employeeJSONTable = Common.Detail.DataGridOperationHelper.ConvertToDataTable(employeeJSONList.OnBoardingEmployee)
employeeJSONTable.PrimaryKey = New DataColumn(){ employeeJSONTable.Columns("EmployeeID")}
End If
lDataSet = objDatabase.GetDataSet(lSqlCommand)
employeeExistingTable = lDataSet.Tables(0)
For Each row As DataRow In employeeExistingTable.Rows
employeeID = row.Item("EmployeeID")
myDataRow = employeeJSONTable.Rows.Find(employeeID)
if (myDataRow Is Nothing) then
employeeJSONTable.ImportRow(row)
End If
Next row
If Not IsNothing(employeeJSONTable.DefaultView) And Request.QueryString.Get("Function") = "HubInbound" Then
objDataView = employeeJSONTable.DefaultView
Elseif Not IsNothing(lDataSet) Then
objDataView = lDataSet.Tables(0).DefaultView
End if

What is DataGridView.Rows.Clear()?

I'm adding programatically some rows in a datagridview every certain time. I want to view in the datagridview the status of certain github repositories, such as if are online, how much commits are in the repos at certain time, etc.
So, when there is timeout, i clear the rows with DataGridView.Rows.Clear() and then i add again the repositories with the updated info.
My code is here:
Dim ok As Integer = 0
DataGridView1.Rows.Clear()
For Each r As RepoURL In _impControllerBpi.GetReposApi
DataGridView1.Rows.Add(DateTimeOffset.Now, "https://github.com/" + r.GetUsr + "/" + r.GetNomRep, "-", "-", "-")
Next
Dim counter = 1
For Each r As RepoURL In _impControllerBpi.GetReposApi
DataGridView1.Rows.Item(counter - 1).Cells.Item(0).Value = DateTimeOffset.Now
DataGridView1.Rows.Item(counter - 1).Cells.Item(2).Value = "Conectando con GitHub"
ok = Await _impController.getRepoGitHub(r, counter)
If ok = 1 Then
DataGridView1.Rows.Item(counter - 1).Cells.Item(0).Value = DateTimeOffset.Now
DataGridView1.Rows.Item(counter - 1).Cells.Item(2).Value = "Conectado"
Else
DataGridView1.Rows.Item(counter - 1).Cells.Item(0).Value = DateTimeOffset.Now
DataGridView1.Rows.Item(counter - 1).Cells.Item(2).Value = "Repositorio no disponible en GitHub"
End If
counter = counter + 1
Next
Dim wreturnCode As Integer = System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf RepeatAction), cancellation.Token)
ok = 0
All works fine without Clear(). But when i clear the rows, in some iteration, when i add the first row, the system throws me a
System.NullReferenceException
Some help? Clear() frees the memory allocated for the collection of rows?
There are serial ways for choice when you really want to clear the data of DataGridView Control.
1.Use for loop to clear the row data one by one.
for (int i = 0; i < dataGridView1.RowCount; i++)
{
dataGridView1.Rows.Remove(dataGridView1.Rows[0]);
}
2.Set DataSource property to NULL directly.
DataGridView.DataSource=null;
If you want to bind DataSet to this control, you’d better setting DataSet to NULL first.
DataSet DataSet1=new DataSet();
DataSet1.clear();
3.Above way may remove all of Tables inside in specified DataSet,so you'd better removing its Table separately.
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("val", typeof(int));
dt.Columns.Add("name", typeof(string));
dt.Rows.Add(1, "good");
ds.Tables.Add(dt);
dt.TableName = "test";
dataGridView1.DataSource = ds.Tables[0];
Hence, you can use following code to clear specified table.
ds.Tables[0].Clear();

Looping through a specific dataset column to check if it contains a certain value

I load a datagridview and am trying to find a quick way of looping through a certain column, given column name....
This is how my datagridview is loaded....
ad = New SqlDataAdapter(sql, con)
ad.Fill(ds, "Fields")
dgvFields.DataSource = ds.Tables("Fields")
dgvFields.ReadOnly = True
dgvFields.RowHeadersVisible = False
dgvFields.Columns(0).Width = 156
dgvFields.Columns(1).Width = 156
dgvFields.Columns(2).Width = 156
dgvFields.Columns(3).Width = 157
'Now I want to be able to loop through dgvfields.columns(3) or column name "Field1a" and check if dgvfields.rows="ValueA"
something along the lines...
For Each row As DataRow In dgvFields.Columns(5)
if dgvfields.rows.value="ValueA" then
'do something
End if
Next
The issue is the type you are looking at for your row... DataRow is for a DataTable not a DataGridViewRow... I would recommend using the index...
Note: this can be done many way's.
For i As Integer = 0 To dgvFields.Rows.Count - 1
If dgvfields.Rows(i).Cells("THE COLUMN NAME").Value="ValueA" Then
'do something
End if
Next

Editing Datable before binding to listview in vb.net

hi this is my code to get datable from query but i need to check for some values like if there is 0 in any column then replace it with N.A.
Dim op As New cad
Dim dt As DataTable = op.Fetchbooks().Tables(0)
Dim sb As New StringBuilder()
Dim rp As System.Data.DataRow
If dt.Rows.Count > 0 Then
ListView1.DataSource = dt
ListView1.DataBind()
DropDownList1.DataSource = dt
DropDownList1.DataTextField = "Description"
DropDownList1.DataValueField = "Description"
DropDownList1.DataBind()
End if
so is there any way to check some values and edit in datable before binding ???
First, if possible i would modify your sql-query in Fetchbooks instead to replace 0 with N.A.. I assume you are querying the database.
However, if you want to do it in memory:
For Each row As DataRow In dt.Rows
For Each col As DataColumn In dt.Columns
If row.IsNull(col) OrElse row(col).ToString = "0" Then
row(col) = "N.A."
End If
Next
Next
Sure: you can iterate through the table, making whatever value replacements are appropriate (assuming that your replacement values are type-compatible with what came from the query).
Something like:
For Each row as DataRow in dt.Rows
if row("columnname") = "left" then
row("columnname") = "right"
Next
Then bind it to the grid, and you should see your updated values.
Once you have the DataTable object you can manipulate it as you need:
For Each rp In dt.Select("COLUMN_A = '0'")
rp("COLUMN_A") = "N.A."
Next
Note that this assumes that COLUMN_A is defined as a string type, not a numeric.
The challenge will be if you intend on saving this data back to it's source and you don't want the original 0 value to be saved instead of N.A.. You could add dt.AcceptChanges immediately after the above loop so that it will appear as the Fetchbooks query had these values all along.

Adding two column values to listbox in vb.net

I have a table named users which has the following columns in it
User_id,user_name,user_pwd,First_Name,Middle_Name,Last_Name and user_type.
I have dataset named dst and created a table called user in the dataset. Now I want to populate listbox with user_Name, First_Name, Last_name of each and every row in the table user.
I am able to add one column value at a time but not getting how to add multiple column values of each row to listbox
Dim dt As DataTable = Dst.Tables("user")
For Each row As DataRow In dt.Rows
lstUsers.Items.Add(row("User_Name"))
Next
Above code works perfectly but I also want to add First_name as well as last_name to the list box at the same time.
Use same approach as you have, but put all values you want in one string.
Dim dt As DataTable = Dst.Tables("user")
For Each row As DataRow In dt.Rows
Dim sItemTemp as String
sItemTemp = String.Format("{0},{1},{2}", row("User_Name"), row("First_Name"), row("Last_Name"))
lstUsers.Items.Add(sItemTemp)
Next
String.Format() function will call .ToString() on all parameters.
In this case if row(ColumnName) is NULL value then .ToString() return just empty string
You have 2 choices:
Using the ListBox:
To use the ListBox, set the font to one that is fixed width like courier new (so that the columns line up), and add the items like this:
For Each row As DataRow In dt.Rows
lstUsers.Items.Add(RPAD(row("User_Name"),16) & RPAD(row("First_Name"),16) & RPAD(row("Last_Name"),16))
Next
The RPAD function is defined like this:
Function RPAD(a As Object, LENGTH As Object) As String
Dim X As Object
X = Len(a)
If (X >= LENGTH) Then
RPAD = a : Exit Function
End If
RPAD = a & Space(LENGTH - X)
End Function
Adjust the LENGTH argument as desired in your case. Add one more for at least one space. This solution is less than ideal because you have to hard-code the column widths.
Use a DataGridView control instead of a ListBox. This is really the best option, and if you need, you can even have it behave like a ListBox by setting the option to select the full row and setting CellBorderStyle to SingleHorizontal. Define the columns in the designer, but no need to set the widths - the columns can auto-size, and I set that option in the code below. if you still prefer to set the widths, comment out the AutoSizeColumnsMode line.
The code to set up the grid and add the rows goes like this:
g.Rows.Clear() ' some of the below options are also cleared, so we set them again
g.AutoSizeColumnsMode = DataGridViewAutoSizeColumnMode.AllCells
g.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal
g.SelectionMode = DataGridViewSelectionMode.FullRowSelect
g.AllowUserToAddRows = False
g.AllowUserToDeleteRows = False
g.AllowUserToOrderColumns = True
For Each row As DataRow In dt.Rows
g.Rows.Add(row("User_Name"), row("First_Name"), row("Last_Name"))
Next
You might solved your problem by now but other users like me might have issue with it.
Above answers given worked for me even but I found a same answer in a simple way according to what I want..
cmd = New SqlCommand("select User_Name, First_Name, Last_Name from User")
Dim dr As SqlDataReader = cmd.ExecuteReader(YourConnectionString)
If dr.HasRows Then
Do While dr.Read
lst.Items.Add(dr.Item(0).ToString & " " & dr.Item(1).ToString & " " & dr.Item(2).ToString)
Loop
End If
This worked for me, maybe wrong way but I found it simple :)
May I suggest you use a ListView control instead of Listbox?
If you make the switch, here's a sample subroutine you could use to fill it up with the data you said you want. Adapt it the way you like; there's much room for improvement but you get the general idea:
Public Sub FillUserListView(lstUsers As ListView, Dst As DataSet)
Dim columnsWanted As List(Of String) = New List(Of String)({"User_Name", "First_Name", "Last_Name"})
Dim dt As DataTable = Dst.Tables("user")
Dim columns As Integer = 0
Dim totalColumns = 0
Dim rows As Integer = dt.Rows.Count
'Set the column titles
For Each column As DataColumn In dt.Columns
If columnsWanted.Contains(column.ColumnName) Then
lstUsers.Columns.Add(column.ColumnName)
columns = columns + 1
End If
totalColumns = totalColumns + 1
Next
Dim rowObjects(columns - 1) As ListViewItem
Dim actualColumn As Integer = 0
'Load up the rows of actual data into the ListView
For row = 0 To rows - 1
For column = 0 To totalColumns - 1
If columnsWanted.Contains(dt.Columns(column).ColumnName) Then
If actualColumn = 0 Then
rowObjects(row) = New ListViewItem()
rowObjects(row).SubItems(actualColumn).Text = dt.Rows(row).Item(actualColumn)
Else
rowObjects(row).SubItems.Add(dt.Rows(row).Item(actualColumn))
End If
lstUsers.Columns.Item(actualColumn).Width = -2 'Set auto-width
actualColumn = actualColumn + 1
End If
Next
lstUsers.Items.Add(rowObjects(row))
Next
lstUsers.View = View.Details 'Causes each item to appear on a separate line arranged in columns
End Sub