Checking matching value and display at gridview - asp.net

I have list of all days in a month (as GridView header) refer to which month is selected by user which then be displayed in GridView.
Display list of Days in a month
Dim dt As New DataTable
Dim col As New DataColumn
dt.Columns.AddRange(New DataColumn(0) {New DataColumn("Date")})
For i As Integer = 1 To gsTotalDD 'gsTotalDD is total of days in a month
dt.Columns.Add(i)
Next
dt.Rows.Add("Status")
gvRptStatus.DataSource = dt
gvRptStatus.DataBind()
I had a table named tblUpload inside the database which storing data that been uploaded together with date of data uploaded.
What I am trying to do is looping through all the header value (list of days) and check either there is day matching with the date of data uploaded. When there is matching value, the status row on the code dt.Rows.Add("Status") will show status done and leave cell empty if no matching days found.
Example : GridView date (fist row), second header column is 1 and check with database has matching value or not. If yes then on (second row) status, at second column will display done.
EDIT
So I came up with checking the matching value like this :
Dim lCnn As New SqlConnection(gsConnString)
Dim lCmd As New SqlCommand
Dim lsCmd As String
Dim dt As New DataTable
Dim newDt As New DataTable
Dim sda As New SqlDataAdapter
Dim dtrow As DataRow = newDt.NewRow()
lCnn.Open()
lCmd.Connection = lCnn
lsCmd = "SELECT DISTINCT DATEPART (d, [date])"
lsCmd &= " FROM dbUpload..tblUpload"
lCmd.CommandText = lsCmd
sda.SelectCommand = lCmd
sda.Fill(newDt)
dt.Columns.AddRange(New DataColumn(0) {New DataColumn("Date")})
For i As Integer = 1 To gsTotalDD 'gsTotalDD is total of days in a month
dt.Columns.Add(i)
value2 = i
For Each col As DataColumn In newDt.Columns
value = newDt.Rows(i - 1).Item(col)
If value = value2 Then
MsgBox("Same value")
End If
Next
Next
By doing this, I manage to check the value but it's not the right way to do it since I wanted to set the status as done if got matching value or leave status empty if vice versa.
Thank you.

Related

get values of dynamic checkboxes

I am dynamically creating checkboxes in VB.Net and an .aspx page, based on values in my db. I'm placing them in a two column table for ease of alignment. this part works fine.
Private Async Function InitForEditAsync() As Task
Dim docList = Await GetLoanApplicationConfigurationDocs()
Dim row = New HtmlTableRow()
Dim cell = New HtmlTableCell()
Dim i = 0
For Each doc In docList
Dim chkBox = New HtmlInputCheckBox()
Dim lbl = New Label()
Dim remainder = i Mod 2
chkBox.ID = "chkDocId" + doc.Id.ToString
lbl.Text = doc.DisplayName
cell.Controls.Add(chkBox)
cell.Controls.Add(lbl)
row.Cells.Add(cell)
cell = New HtmlTableCell()
If remainder <> 0 OrElse i = docList.Count() - 1 Then
tblEdit.Rows.Add(row)
row = New HtmlTableRow()
End If
i += 1
Next
End Function
Now I need to retrieve the values without knowing the id's but am not having any luck. I tried this:
For Each chkBox As HtmlInputCheckBox In pnlEdit.Controls.OfType(Of HtmlInputCheckBox)
but the checkboxes are not returned in the list of controls. The table is, but there are no rows in the table object when I explored it in the control collection and when I tried this:
For Each row As HtmlTableRow In tblEdit.Rows.OfType(Of HtmlTableRow)
If it will help, here is a Snip of the UI and the HTML that is created:
Any suggestions are appreciated. Thanks in advance.
Based on some ideas I got from another site, I'm going to rewrite this using the asp:CheckBoxList. apparently it binds like a datagrid and you can enumerate through it. Seems like what i need.
UPDATE: Everything I posted to start was resolved with five lines of code! "cblDocList is my asp CheckboxList and docList is my ienumerable of objects.
cblDocList.RepeatColumns = 2
cblDocList.DataSource = docList
cblDocList.DataTextField = "DisplayName"
cblDocList.DataValueField = "Id"
cblDocList.DataBind()
It’s something you can do through a loop for each row and each cell or using Linq to have only cells that have controls of type HtmlInputCheckBox inside.
I have simplified your code to be able run that here also shows you an example to achieve your task. Obviously you must change following your exigences .
Hope I well understood :)
Dim tblEdit As New HtmlTable
For k As Integer = 0 To 10
Dim cell = New HtmlTableCell()
Dim row = New HtmlTableRow()
Dim chkBox = New HtmlInputCheckBox()
Dim lbl = New Label()
Dim remainder = k Mod 2
chkBox.ID = "chkDocId_" + k.ToString
chkBox.Checked = remainder = 0
lbl.Text = "Text indicator of CheckBox nr:" + k.ToString
cell.Controls.Add(chkBox)
cell.Controls.Add(lbl)
row.Cells.Add(cell)
cell = New HtmlTableCell()
tblEdit.Rows.Add(row)
Next
Dim checkBoxes As IEnumerable(Of HtmlInputCheckBox) =
(From mRow In tblEdit.Rows).Select(Function(mr)
Dim cb = (From cc In CType(mr, HtmlTableRow).Cells
Where CType(cc, HtmlTableCell).Controls.OfType(Of HtmlInputCheckBox).Count > 0
Select CType(cc, HtmlTableCell).Controls.OfType(Of HtmlInputCheckBox)()(0)).FirstOrDefault
Return CType(cb, HtmlInputCheckBox)
End Function).ToList
For Each checkBox In checkBoxes
Debug.WriteLine("CheckBox ID: {0} Checked: {1} ", checkBox.ID, checkBox.Checked)
Next

Merging distinct from one column and sum from others in vb.net

I have Multiple Rows of same product with different Qty.
I want single row of each product by doing some of Qty in datatable in vb.net
So you want to group by the product and sum the quantity per group?
You could use LINQ's GroupBy + Sum and fill a second table with the same schema:
Dim productGroups = dt.AsEnumerable().GroupBy(Function(row) row.Field(Of String)("Product"))
Dim aggregatedTable As DataTable = dt.Clone() ' empty table, same columns
For Each grp In productGroups
Dim newRow = aggregatedTable.Rows.Add()
Dim sumOfQuantity As Int32 = grp.Sum(Function(row) row.Field(Of Int32)("Qty"))
newRow.SetField("Product", grp.Key)
newRow.SetField("Qty", sumOfQuantity)
Next
The same with query syntax if you prefer it:
Dim productGroups = From row In dt.AsEnumerable()
Group row By Product = row.Field(Of String)("Product") Into Group

Refresh ComboBox in Windows form with datasource retains value even when datasource is empty

I have 2 comboboxes, cmbstud and cmbhostel. They are filled from the database by binding the datasource to the datatable. As I update, the cmbstud updates accordingly. When I update the last record the datatable empties, but cmbstud still retains the value. Cmbhostel data is bound to change index of cmbstud.
In the form load event I have this code:
Dim cmd As New SqlCommand("SELECT stud_id,name FROM student_details WHERE stud_id NOT IN (SELECT stud_id FROM student_details WHERE hostel_id!=0)", sqlcont.Conn)
Dim dr As SqlDataReader = cmd.ExecuteReader
Dim dat As New DataTable
Dim j As Integer
For j = 0 To dat.Rows.Count - 1
dr.Read()
Next
dat.Load(dr)
cmbstud.DisplayMember = "name"
cmbstud.ValueMember = "stud_id"
cmbstud.DataSource = New BindingSource(dat, Nothing)
dr.Close()
sqlcont.Conn.Close()
In my btnhostel for updating I have the following queries implemented and the following code to reload the form to refresh my datasources:
"UPDATE hostel SET in_use=in_use+1 WHERE hostel_id=#hostid"
"UPDATE student_details SET hostel_id=#hostid where stud_id=#stud_id"
frmallocateHostel_Load(Nothing, Nothing)
Cmbstud index change evnt code:
Dim sqcm5 As New SqlCommand("Select hostel.hostel_id,hostel.hostel_name From hostel Inner Join student_details On student_details.gender = hostel.hostel_gender where student_details.stud_id =" & cmbstud.SelectedValue.ToString & " ", sqlcont.Conn)
Dim datreadr5 As SqlDataReader = sqcm5.ExecuteReader
Dim dt5 As New DataTable
Dim n As Integer
For n = 0 To dt5.Rows.Count - 1
datreadr5.Read()
Next
dt5.Load(datreadr5)
cmbhostel.ValueMember = "hostel_id"
'asign value & display member b4 datasource to avoid errors
cmbhostel.DisplayMember = "hostel_name"
cmbhostel.DataSource = dt5
There are some similar questions: ComboBox has its old value after Clear(); however, they don't address my issue.
changing this did the trick:
Dim b As New BindingSource()
b.DataSource = dat
cmbstud.DataSource = b
b.ResetBindings(False)

Select keyword require > instead of =

if i use = instead of > in line below
TextBox1.Text = "regdate > '12/12/2012 8:27:09'";
it return me zero rows . Any reason ?
DataView dv1 = new DataView ();
DataSet ds = new DataSet ();
DataTable dt = new DataTable();
/*
col1 col2 col3 col4 col5
1 sw#yahoo.com sw Stephen Walther 12/12/2012 8:27:09 PM
2 as#yahoo.com as Al Stevens 12/12/2012 8:27:09 PM
*/
// Here is the code and criteria for selecting few rows based on datetime .
TextBox1.Text = "regdate > '12/12/2012'";
//connection created
SqlConnection con = new SqlConnection(SqlDataSource1.ConnectionString);
con.Open();
SqlDataAdapter da = new SqlDataAdapter ("SELECT * FROM users",con);
da.Fill (ds);
// filtering criteria applied .
DataRow[] dr = ds.Tables["Table"].Select(TextBox1.Text);
//columns created
dt.Columns.Add("col1", typeof(int));
dt.Columns.Add("col2", typeof(string));
dt.Columns.Add("col3", typeof(string));
dt.Columns.Add("col4", typeof(string));
dt.Columns.Add("col5", typeof(DateTime));
// data added
foreach (DataRow item in dr)
{
dt.Rows.Add(item.ItemArray);
}
// view created
dv1 = dt.DefaultView ;
GridView1.DataSourceID = string.Empty;
GridView1.DataSource = dv1 ;
Page.DataBind();
Because it's a datetime field, so it will compare the whole date and time value, not just the date.
The value 12/12/2012 8:27:09 PM and 12/12/2012 are not the same, because the 12/12/2012 gets expanded to the 12/12/2012 12:00:00 AM value to be comparable to the datetime value. The datetime value doesn't get truncated to be comparable to the date value.
Generally when data types doesn't match for a comparison or calculation, the smaller type gets expanded to the larger type, so that there is no unintentional data loss.
Because the time component is stopping the match - it is trying to match the date AND time.
You could try to use some kind of DATEDIFF function to just match the date portion
How to test two datetimes for equality in T-SQL (ignoring their time components)?
BUT - when amending the code just be really careful with this - not to start putting text box input into the SQL statement. Injection attack risk aplenty.
I think you are OK as it stands but....
The database stores the date in (about) millisecond resolution. When "12/12/2012 8:27:09 PM" is displayed, there is probably a millisecond part that is not displayed, but will throw off a comparison with a date that doesn't specify those milliseconds.
The ">" comparison will succeed because the stored date is higher than your specified date, precisely because of those milliseconds.

ARRGH! Duplicate results in from a query, but only sometimes

UPDATE>>>> If I run this on localhost, their is no duplication of data, but on the site there is. Does that help to give people an idea of what may be going on?
I have an application built by someone else that is returning results from a socket call when the end user types in a little product info, and hits submit. The application returns the results, but it sometimes displays the results twice. For example, if I click submit on the application to do a search for a product, it may come back with the correct one, two, or three records (as there could be results from 1-3 locations), or it may repeat all those results twice. (Ie.: if there were two records returned, it might simply display the info from the two records, or it may display the results from the two records in the first two rows of the , and then repeat rows 1 & 2 in rows 3 & 4.) Continuing to click submit on that page will (it appears randomly) change the resulting displayed data - cycling between one set of results and two.
Any ideas on what may be causing this? I've included the bit of code I think is involved. I inherited this code, and am trying to make it work, but I'm new to this type of application and only intermediate at best in asp.net. Thank-you in advance to anyone who can shed some light!!
Protected Sub displayTableOne(ByVal records() As String)
Dim dt As New DataTable()
Dim values() As String = {""}
Dim i As Integer = 0
Try
Dim Row() As String = {"Company", "Piece", "Description", _
"Location", "Available", "Purchased", "Ship Date"}
#Create the columns
Dim column1 As New DataColumn("Company", GetType(String))
Dim column2 As New DataColumn("Piece", GetType(String))
Dim column3 As New DataColumn("Description", GetType(String))
Dim column4 As New DataColumn("Location", GetType(String))
Dim column5 As New DataColumn("Available", GetType(String))
Dim column6 As New DataColumn("Purchased", GetType(String))
Dim column7 As New DataColumn("Ship Date", GetType(String))
dt.Columns.Add(column1)
dt.Columns.Add(column2)
dt.Columns.Add(column3)
dt.Columns.Add(column4)
dt.Columns.Add(column5)
dt.Columns.Add(column6)
dt.Columns.Add(column7)
If (records.Length > 1) Then
For i = 0 To records.Length - 2 Step 1
values = Split(records(i), "|")
Dim l As Integer = 0
Dim dr As DataRow
dr = dt.NewRow()
If values(0) = "05" Then
If (values.Length > 4) Then
dr(Row(0)) = values(1)
dr(Row(1)) = values(2)
dr(Row(2)) = values(13)
dr(Row(3)) = values(17)
dr(Row(4)) = values(7)
dr(Row(5)) = values(15)
dr(Row(6)) = values(16)
End If
dt.Rows.Add(dr)
End If
Next
If values(23) = "Error" Then
invalidMessage()
Else
#Bind the DataTable to the DataGrid
Table1.Visible = True
Table1.DataSource = dt
Table1.DataBind()
End If
End If
Catch ex As Exception
invalidMessage()
Finally
Array.Clear(records, 0, records.Length)
Array.Clear(values, 0, values.Length)
End Try
End Sub

Resources