DataTable: create rows dynamically according to the number of checkboxes selected in the checkbox List - datatable

I am trying to create a DataTable the number of rows of which needs to be created automatically according to the number of checkboxes checked in my checkbox list:
Private Function GetRoomTypeIds() As DataTable
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn(1) {New DataColumn("Id", GetType(Integer)), New DataColumn("RoomTypeId", GetType(Integer))})
dt.Rows.Add(txtId1.Text, chkRoomTypes.SelectedValue)
Return dt
End Function
I would need to add something like:
"For Each Checkbox checked in my checkbox list generate the corresponding number of rows."
Thanks

I solved as per below code:
Private Function GetRoomTypeIds() As DataTable
Dim selectedItems = From s In chkRoomTypes.Items.Cast(Of ListItem)
Where s.Selected
Select s
Dim itemTable As DataTable
itemTable = New DataTable("SelectedItems")
Dim column1 As DataColumn = New DataColumn("RateTypeId")
column1.DataType = System.Type.GetType("System.Int32")
Dim column2 As DataColumn = New DataColumn("RoomTypeId")
column2.DataType = System.Type.GetType("System.Int32")
itemTable.Columns.Add(column1)
itemTable.Columns.Add(column2)
Dim Row As DataRow
For Each item In selectedItems
Row = itemTable.NewRow()
Row("RateTypeId") = Convert.ToInt32(txtId1.Text)
Row("RoomTypeId") = item.Value
itemTable.Rows.Add(Row)
Next
Return itemTable
End Function
Thanks

Related

How do you add your queried datatable results into a new datatable

Can someone please help me fill my queried results into the existing datatable or a new datatable
''dt is filled with data from a csv file.
Dim dataRows As DataRow() = dt.Select("[Calendar year TEXT] = '2020'")
dt.Clear() 'Clear the datatable
dt.Rows.Add(dataRows) 'Add the result to the existing datatable or a new databletable if possible ?
So I've figured it out.
The reason I need a new DataTable is that I need to use it again in its original form later.
I could not attach the DataRow collection to my display control which is why I needed a new DataTable with the filtered results.
Private Function FilterDataTable(ByVal strQuery As String, ByVal dtRaw As DataTable)
Dim dataRows As DataRow() = dtRaw.Select(strQuery)
Dim dtFiltered As DataTable
dtFiltered = dtRaw.Clone() 'This is very important.
For Each drow As DataRow In dataRows
dtFiltered.ImportRow(drow) 'Add each filtered row to new DataTable.
Next
Return dtFiltered
End Function
Your dt.select will return an array of Datarow pointing to the rows in the datatable dt. Your dt.clear then clears the datatable and so will empty the dataRows array leaving you nothing left.
I'm not clear exactly what you are trying to do. I'm guessing you have a table that you want to filter and then discard all rows that don't match, leaving you a datatable to work with.
If so, here's a few options:
Work with the datarow array directly rather than the datatable. Is there really any need to convert the rows back to a datatable?
Create a new datatable to add the rows to, but don't clear the original table:
Dim dt As New DataTable ' Assume this is your populated table
Dim dataRows As DataRow() = dt.Select("[Calendar year TEXT] = '2020'")
Dim dtResults As DataTable = dt.Clone()
For Each row As DataRow In dr
dtResults.ImportRow(row)
Next
bare in mind any changes you make to the rows in dtResults will also affect the rows in dt as they both contain the same data
Depending on the size of your table and whether or not you really want to discard non matching rows, you could just remove all rows that don't match then work with the result:
Dim i As Integer = dt.Rows.Count - 1
While i >= 0
If dt(i).Item("Calendar") <> "Your test here" Then dt.Rows.Remove(dt(i))
i -= 1
End While

How do i set the celltype for a datagrid column?

I am adding a new column to a datagrid to store a row total of qty*Cost
When I try to add the column I get an exception saying
System.InvalidOperationException: 'Column cannot be added because its CellType property is null.'
I've tried to set the cell type but I can't get the type right
Dim dt As DataTable = Me.DsOppQuoteDetail.tblOppQuoteDetail
Dim dr As DataRow
Dim dc As New DataGridViewColumn
With dc
.HeaderText = "Item Total"
.Name = "UnitTotal"
.CellType = DataGridTextBox
End With
DGV_OppQuoteDetail.Columns.Insert(6, dc)
Setting the CellType to DataGridTextBox produces an error
If I change the the column to:
Dim dc As New DataGridTextBoxColumn
With dc
.HeaderText = "Item Total"
End With
DGV_OppQuoteDetail.Columns.Insert(6, dc)
then I can't insert it because it's the wrong type for the DataGrid.Insert command
Dim dc As New DataGridViewTextBoxColumn
dc.HeaderText = "SomeText"
dc.Name = "colWhateverName"
DGV_OppQuoteDetail.Columns.Add(dc)
Try this and let me know. Only slightly different in terms of wording. Also from your code snippet it seems fine but make sure you don't add any rows before adding a column.

how to show combobox in datagrid in vb.net

I have this query below and I want to show items that sold depending on sales_id without repeat the old ids. And another question how to make a combo box data grid view:
Private Sub filldatagrid()
Dim myTableName As String
myTableName = txtid.Text
winclass.filldatagrid(DataGridView1, "select inventory.inv_name,sales_data.sales_id,sales_data.quantity,sales_data.sum_total from sales_data,inventory where sales_data.inv_id=inventory.inv_id ")
DataGridView1.Columns(0).HeaderText = "ID"
DataGridView1.Columns(0).Visible = True
DataGridView1.Columns(1).HeaderText = "name"
DataGridView1.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End Sub

Bind Objects To DataGridview and Reorder Column

I want to bind the object list to dataGridView.
Now i want the desired column to be the way i definde them. i.e., I want the objects to be order the way i want.
Like
var dataSource = linkItemListCommon.Select(x => new DataToBind { Select = x.Default, FileName = x.Text, CurrentDate = x.Date+" "+x.Time , PreviousDate = string.Empty, Size = x.Size }).ToList();
var filenamesList = new BindingList<DataToBind>(dataSource);
dgvDownLoadMaster.DataSource = filenamesList;
I want the datagrid columns to be in the order that i define.
Like here i expect them to be in order given below:
Select FileName CurrentDate PreviousDate Size
But the column list is appearing not as per my requirements.
How to Do that.Please help.
Create columns by hand and then you can order them easily. You can add columns trough designer and just set each column DataPropertyName to corresponding field.
Or you can create each column programmatically:
var col = new DataGridViewTextBoxColumn();
col.DataPropertyName = "Select ";
col.HeaderText = "Select";
col.Name = "ColSelect";
dgvDownLoadMaster.Columns.Add(col);
you have to do this for each column and do it before databinding.

linq on datarow to get index of specific item

I have datatable which it first row is headers
I need specific column for this datatable according to the header
I know how to get the column if know its index.
The problem is how to get the index
Dim columnIndex as integer
Dim headerRow As DataRow = dt.Rows(0)
Dim colHeader As string ="abc"
columnIndex=???
Dim result = dt.Rows.Cast(Of DataRow)().[Select](Function(row) row(columnIndex)).Distinct().ToList()
Thanks
You may use the dt.Rows.IndexOf
Dim ValueToSearch AS string = ...
columnIndex = dt.AsEnumerable().Where(Function(x) x.Field(of String)(colHeader) = ValueToSearch).Select(Function(x) dt.Rows.IndexOf(x)).SingleOrDefault()
The above will work if the where clause returns only one or zero rows. If this is not true then you may dismiss the SingleOrDefault and then loop through the results, ie:
columnIndex = dt.AsEnumerable().Where(Function(x) x.Field(of String)(colHeader) = ValueToSearch).Select(Function(x) dt.Rows.IndexOf(x))
For Each i in columnIndex
Console.WriteLine("Value found in row with index " + i.ToString())
Next
Giannis

Resources