How to select checked item in data Grid using linq - vb.net

i have a data grid (using component one's control) and this data grid have a check box value item to select some of the rows, the given below is my grid
i use the check box to select rows for delete or update
at this moment am using for loop to iterate through my grid
i think in .net using linq is more better than for loop
given below is my code to iterate through grid using for loop
Private Sub deleteGtab81()
Dim intcount As Integer
Dim intdistid As Integer
Dim command, commandReader As New NpgsqlCommand
command.Connection = GenConnection()
commandReader.Connection = command.Connection
command.CommandType = CommandType.Text
commandReader.CommandType = CommandType.Text
For intcount = 0 To grdDistricts.Rows.Count - 1
If grdDistricts(intcount, "S").ToString <> "" Then
If grdDistricts(intcount, "S").ToString = 1 Then
intdistid = grdDistricts(intcount, "talukid").ToString()
command.CommandText = "delete from gtab81 where talukid='" & intdistid & "' "
command.ExecuteNonQuery()
End If
End If
Next
grdDistricts.Rows.Clear()
FillGrddistricts()
FillCbodistricts()
End Sub
So how to use linq to get the selected rows ?
NOTE : code is written in vb.net
T.I.A

I've never really tried to use LINQ against a DataGridViewRowCollection, but I suppose you should write something like that:
C#
IList<int> result = (from row in grdDistricts.Rows.OfType<DataGridViewRow>()
where !string.IsNullOrEmpty(row.Cells["S"].Value.ToString()) &&
(int)row.Cells["S"].Value == 1
select (int)row.Cells["talukid"].Value).ToList();
VB.NET
Dim list As IList(Of Integer) = (From row In grdDistricts.Rows.OfType(Of DataGridViewRow)() _
Where Not String.IsNullOrEmpty(row.Cells("S").Value.ToString()) AndAlso _
row.Cells("S").Value = 1 _
Select DirectCast(row.Cells("talukid").Value, Integer)).ToList()
This will select all yours "talukid" and place them in a list.

Related

How to check value from looping every rows with spesific coloumn on datatable?

I want to loop every rows my datatable, the value from specific coloumn is 1,2,3. But, The value has checked only number 1. How to check every value from looping?
Dim cmd2 As New SqlCommand("Select * from Compartment where OrderFK='1254'", con)
dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection)
Dim dt As New DataTable()
dt.Load(dr) 'Here from datareader
For Each row As DataRow In dt.Rows
Dim x As Integer = dt.Rows(0)("CNumber").ToString
If x = 2 Then
Loading_No.Value = 2
Else
loading_no.value = "Empty"
End If
Next
Thank you,
If you loop with a foreach with the sets of rows retrieved by your query you should use the foreach indexer (row) to read the current value of the CNumber column, but instead of adding immediately to the TextBox add the retrieved value to a StringBuilder appending the current value to the previous read ones. At the end of the loop write everything in the TextBox value property
Dim cmd2 As New SqlCommand("Select * from Compartment where OrderFK='1254'", con)
dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection)
Dim dt As New DataTable()
dt.Load(dr) 'Here from datareader
Dim sb = new StringBuilder()
For Each row As DataRow In dt.Rows
Dim value = row("CNumber").ToString()
if value = "1" OrElse value = "2" OrElse value = "3" Then
sb.Append(row("CNumber").ToString & "," )
End If
Next
If sb.Length = 0 Then
sb.Append("Empty")
Else
' remove the last comma '
sb.Length = sb.Length - 1
End If
loading_no.Value = sb.ToString()
Notice also that you can remove the if test inside the loop modifying your query to retrieve only the records that you are interested
Dim cmdText = "Select * from Compartment where OrderFK='1254' " & _
"AND CNumber IN(1,2,3)"
To find out how many rows your loop went through just put a counter into the loop. What I am wodering about is this line:
Dim x As Integer = dt.Rows(0)("CNumber").ToString
You declare x to be an integer and assign a string to it?

Filter and sort datagridview

I have created an item list in which all items are loaded, and I need to filter the data according to the text entered in the textbox.
Please guide me how to filter and sort data, I have created the fallowing code
Private Sub loadsearchitems(item As String)
dgvsearchitem.ScrollBars = ScrollBars.Vertical
On Error Resume Next
con = New System.Data.OleDb.OleDbConnection(connectionString)
con.Open()
Dim ds As DataSet = New DataSet
Dim adapter As New OleDb.OleDbDataAdapter
sqlstr = "SELECT Imaster.icode, Imaster.iname & ' ' & MfgComTab.comname as[Iname], Imaster.unitcode, Imaster.tax,Unit.unitname FROM ((Imaster INNER JOIN MfgComTab ON Imaster.mccode = MfgComTab.mccode) INNER JOIN Unit ON Imaster.unitcode = Unit.unitcode) WHERE (Imaster.isdeleted = 'N') AND Imaster.comcode=#comcode AND Imaster.iname like '%' & #item & '%' order by iname asc "
adapter.SelectCommand = New OleDb.OleDbCommand(sqlstr, con)
adapter.SelectCommand.Parameters.AddWithValue("#comcode", compcode)
adapter.SelectCommand.Parameters.AddWithValue("#iname", item)
adapter.Fill(ds)
If ds.Tables(0).Rows.Count > 0 Then
dgvsearchitem.DataSource = ds.Tables(0)
dgvsearchitem.Columns("unitname").Visible = False
dgvsearchitem.Columns("unitcode").Visible = False
dgvsearchitem.Columns("icode").Visible = False
dgvsearchitem.Columns("tax").Visible = False
dgvsearchitem.Columns("Iname").Width = 371
Else
ds.Dispose()
End If
con.Close()
End Sub
But in the above code the application is slow because every time any text is entered a query is executed. Please tell me any solution where query is executed only once and when we enter the text it only search the items by wild card and filter it.
If you initially set the DataGridView with all the records, then you could avoid to go again to the database to extract your data in a filtered way. You have already extracted everything, so you could simply set the DataSource with a DataView filtered locally
' Code that loads initially the grid
sqlstr = "SELECT Imaster.icode, Imaster.iname .....FROM ...." ' NO WHERE HERE
....
dgvsearchitem.DataSource = ds.Tables(0).DefaultView
Now in your loadsearchitems instead of executing again a query against the database you could take the datasource and set the RowFilter property
Dim v as DataView = CType(dgvsearchitem.DataSource, DataView)
v.RowFilter = "Imaster.comcode='" & compcode & "' AND Imaster.iname like '%" & item & "'%'"
Note how the RowFilter property doesn't understand the use of parameters, so if it is possible for your comcode field to contain single quotes you need to add a some form of doubling the quotes (a String.Replace will do) to avoid a syntax error. And yes, there is no worry for Sql Injection on a DataView (it is a disconnected object and whatever your user types in the compcode field it cannot reach the database)

Error loading sql parameters in a loop, VB.Net

I am currently working in Microsoft visual studio express 2013 with an sql back end. I am trying to run a loop through 2 comboboxes and a datetimepicker for any instance a checkbox is checked. However, I am running into an error that reads "System.ArgumentException: No Mapping exists from Object type system.windows.forms.datetimepicker to a known managed provider native type." When I run the code I have put a watch on the parameter value and it is not saving the data into the variable before the sql command fires. I think I need to store the variable in a different way to allow access to the variable. Here is my code:
Try
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As New SqlCommand("SELECT isnull(max(AuditID) + 1, 1) as 'AuditID' FROM table1", conn1)
Dim reader1 As SqlDataReader = comm1.ExecuteReader
reader1.Read()
Dim AuditID As Integer = reader1("AuditID")
reader1.Dispose()
'Loop through all checkboxes and write into sql tables
Dim Run As Integer
For Run = 1 To 5
Dim LineItem = DirectCast(Me.Controls("CB" & Run), CheckBox)
If LineItem.Checked = True Then
Dim DateTime = DirectCast(Me.Controls("DTP" & Run), DateTimePicker)
Dim Frequency = DirectCast(Me.Controls("CBWeek" & Run), ComboBox)
Dim Repeat = DirectCast(Me.Controls("CBRepeat" & Run), ComboBox)
'sql statements
'select ID
Using conn2 As New SqlConnection(connstring)
conn2.Open()
Using comm2 As New SqlCommand("SELECT isnull(max(AuditID) + 1, 1) as 'ID' FROM table1", conn1)
Dim reader As SqlDataReader = comm2.ExecuteReader
reader.Read()
Dim ID As Integer = reader("ID")
reader.Dispose()
'Insert into table audit line
Using conn3 As New SqlConnection(connstring)
conn3.Open()
Using comm3 As New SqlCommand("INSERT INTO table1 (ID, AuditID, DateStart, Freq, repeats) " _
& "VALUES (#ID, #AuditID, #DateStart, #Freq, #Repeats)", conn3)
With comm3.Parameters
.AddWithValue("#ID", ID)
.AddWithValue("#AuditID", AuditID)
.AddWithValue("#DateStart", DateTime)
.AddWithValue("#Freq", Frequency)
.AddWithValue("#Repeats", Repeat)
End With
comm3.ExecuteNonQuery()
End Using
conn3.Close()
End Using
End Using
conn2.Close()
End Using
End If
Next
End Using
conn1.Close()
End Using
Catch ex As Exception
MsgBox(ex.ToString)
My try statement stop my code on this line:
comm3.ExecuteNonQuery()
However, I know that this error is coming from when I add my parameters, specifically these 3 lines:
.AddWithValue("#DateStart", DateTime)
.AddWithValue("#Freq", Frequency)
.AddWithValue("#Repeats", Repeat)
I am trying to get tese variables with a loop statement based on the design name here:
Dim DateTime = DirectCast(Me.Controls("DTP" & Run), DateTimePicker)
Dim Frequency = DirectCast(Me.Controls("CBWeek" & Run), ComboBox)
Dim Repeat = DirectCast(Me.Controls("CBRepeat" & Run), ComboBox)
It does not seem like the program likes using these dimensions above to be inserted into the sql table. Does anyone know a way I can carry these values over to the sql parameters statement?
There are a number of things I would do differently. First and always, use Option Strict, it will catch some of the type conversion you have going on.
I would get the controls from an explicit list rather then fetching from Controls. Just make a few arrays to hold the control refs so you do not need to to find them in the collection:
Private DTPs As DateTimePicker() = {DTP1, DTP2...}
This will avoid the need to cast them, fewer hoops and implied converts like "DTP" & Run:
Dim dt As DateTime ' vars for the SQL
Dim freq As Integer
For Run As Integer = 0 To 4
dt = DTPs(Run).Value
freq = cboFreq(Run).SelectedValue
...
I have fixed the problem, I needed to put my loop variables into .value type variables. I added this to fix it:
Dim DateTime = DirectCast(Me.Controls("DTP" & Run), DateTimePicker)
Dim Frequency = DirectCast(Me.Controls("CBWeek" & Run), ComboBox)
Dim Repeat = DirectCast(Me.Controls("CBRepeat" & Run), ComboBox)
Dim Time As Date = DateTime.Value
Dim Freq As Integer = Frequency.SelectedValue
Dim Again As Integer = Repeat.SelectedValue

Loop SQL if has Rows then continue

I am trying to run this loop to run if the results continue to have rows. So basically if my sql statement continues to return a row on ssql = "SELECT TOP 1 * from [OrderHeader] Where ([IsisDownloadDate] is null or [IsisDownloadDate] = '')"
then run submit to webrequest, then return a value, then submit that value to the same row and update that column
So basically I just want it to keep updating the next row as long as ssql keeps returning rows, and if it does not return any rows then stop.
I got everything to work, besides the continuous looping issue
Here is the code:
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim objDR As SqlClient.SqlDataReader
Dim objCommand As SqlClient.SqlCommand
Dim ConnectionString As String = "Data Source=localhost;Initial Catalog=datarep;user id=sa;password=test123;"
Dim objConnection As SqlClient.SqlConnection
Dim ssql As String
objConnection = New SqlClient.SqlConnection(ConnectionString)
ssql = "SELECT TOP 1 * from [OrderHeader] Where ([IsisDownloadDate] is null or [IsisDownloadDate] = '')"
If objConnection.State <> ConnectionState.Open Then
objConnection.Open()
End If
objCommand = New SqlClient.SqlCommand(ssql, objConnection)
objDR = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
objCommand = Nothing
If objDR.HasRows Then
While objDR.Read()
Dim objSO As New WebReference.SalesOrder
Dim objBTAddr As New WebReference.BillToAddress
Dim objSTaddr As New WebReference.ShipToAddress
Dim objAddr As New WebReference.Address
Dim objPart() As WebReference.SalesOrderPart
Dim objMisc As New WebReference.SalesOrderMiscCharges
Dim objPayment As New WebReference.Payment
Dim objCreditCard As New WebReference.SalesOrderCreditCard
Dim objApproval As New WebReference.SalesOrderCreditCardApproval
objSO.OrderNumber = "69355522"
objSO.CompanyId = "301"
objSO.CustomerNumber = "5838303"
objSO.Code = "I"
objSO.PONumber = objDR("OrderNumber").ToString()
objSO.Source = "TAW.COM"
objSO.OrderDate = Format(Date.Now, "MM/dd/yy")
objSO.RequiredDate = Format(Date.Now, "MM/dd/yy")
objSO.ShipCode = "UPG"
objSO.EmployeeId = "1"
objAddr.Name = "José Peña,EPS H-1607"
objAddr.Address1 = "LÄRKGATAN 9"
objAddr.City = "Québec"
objAddr.Country = "US"
objAddr.State = "CA"
objAddr.Zip = "90220"
objSTaddr.Address = objAddr
'objSTaddr.Phone = "310-900-5509"
objBTAddr.AccountNumber = "595522"
objBTAddr.Address = objAddr
objSO.BillToAddress = objBTAddr
'turn on for .88
'objSO.ShipTo = objSTaddr
'objSO.ShipTo.Phone = objSTaddr.Phone
ReDim objPart(1)
objPart(0) = New WebReference.SalesOrderPart
objPart(0).PartNumber = "EVE510-621"
objPart(0).PartId = "EVE"
objPart(0).Quantity = 1
objPart(0).Price = 39.99
objPart(0).Description = "PWRAID SPCR"
objSO.Parts = objPart
Dim ws As New WebReference.WebServiceTyped
Dim result As WebReference.SubmitOrder = ws.SubmitSalesOrder(objSO)
Dim ordernum As String = result.OrderId
Dim s As String = "Data Source=localhost;Initial Catalog=datarep;user id=sa;password=test123;"
Dim sql As String
Dim con As New SqlConnection
con = New SqlConnection(s)
con.Open()
sql = "WITH UpdateList_view AS ( SELECT TOP 1 * from [OrderHeader] Where ([IsisDownloadDate] is null or [IsisDownloadDate] = '') ) update UpdateList_view set [IsisDownloadDate] = '" & result.OrderId & "'"
Dim cmd As New SqlClient.SqlCommand(sql, con)
cmd.ExecuteNonQuery()
con.Close()
End While
End If
objDR.Close()
objDR = Nothing
End Sub
Besides the whole, why would you want to do it this way issue, the problem is that you are only selecting one row. Your while loop goes through that singular row then exits. There are a lot of issues with this code though and I would recommend that you do not do it this way.
Let's go through the code a little bit. Let's say there are two rows that fit this criteria, row J and row 6. You select top 1 and you get row J back. Your If objDR.HasRows will evaluate to true and you will go into the while condition. After you read and update, you go back to the while condition. You already read row J and your vb.net code is not aware of what else is in the database, so we exit the while loop and exit the sub.
I recommend selecting all the rows that fit your criteria right off the bat. Selecting all of your data instead of top 1 will be better than selecting what you want one row at a time from the database because it is expensive to go out and connect to the database. Your way, you will be connecting to the database twice for each row that fits the criteria. My way, you will connect once for each row plus one more time at the beginning. If you are updating a lot of rows this will be a huge difference. Your sql should look more like
SELECT UniqueId from [OrderHeader] Where ([IsisDownloadDate] is null or [IsisDownloadDate] = '')
Now when you loop, you are going through all of the data. I also recommend that when you update the data make sure you use a parameter that will update the specific row you are looking at, some sort of unique id is usually best. In reality, you don't need a cte for this either. Something like:
sql = New SqlCommand("UPDATE UpdateList_view SET [IsisDownloadDate] = #OrderId WHERE UniqueId = #ID", dbConn)
sql.Parameters.AddWithValue("#OrderId", result.OrderId)
sql.Parameters.AddWithValue("#Id", objDR.GetInt32(0))
Note, objDR.GetInt32(0) would be setting the #Id parameter to the unique id that would be selected in the first sql query. Also, please please look at how I have added parameters to the sqlCommand. You should get into the habit of coding this way because update UpdateList_view set [IsisDownloadDate] = '" & result.OrderId & "'" leaves you open to sql injection.
Lastly, you may want to consider doing a sql bulk update rather than updating each row one at a time. This is probably a good place to start.

Getting selected listbox items values to display in another listbox using vb 2008

I have a form with a 2 listboxes. Here, listbox1 is populated with names of actors and actresses. If a name is selected from listbox1, listbox2 should show the title(s) of movie(s) where that name is involved. If another name is selected, listbox2 will show title(s) of movie(s) that 2 name is involved.
Call Connect()
With Me
STRSQL = "select mTitle from selectmovie where cName = '" & lstNames.SelectedItem & "'"
Try
myCmd.Connection = myConn
myCmd.CommandText = STRSQL
myReader = myCmd.ExecuteReader
If (myReader.Read()) Then
myReader.Close()
myAdptr.SelectCommand = myCmd
myAdptr.Fill(myDataTable)
lstTitle.DisplayMember = "mTitle"
lstTitle.ValueMember = "mTitle"
If myDataTable.Rows.Count > 0 Then
For i As Integer = 0 To myDataTable.Rows.Count - 1
lstTitle.Items.Add(myDataTable.Rows(i)("mTitle"))
Next
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End With
There's no error. When I select 1 item the result is correct but it leaves many space..here the screen shot of my form: http://www.flickr.com/photos/92925726#N06/8445945758/in/photostream/
The output becomes worse when I selected actor3: http://www.flickr.com/photos/92925726#N06/8445945724/in/photostream/
Your main problem seems to be that you do not clear your lstTitle control before re-loading it with the new selection. Therefore, each time you select a new name, it will add all the titles for that name to the existing list of titles that are already loaded. Also, instead of using an integer to iterate all the indexes, it is easier to just use a For Each loop:
lstTitle.Items.Clear()
For Each row As DataRow In myDataTable.Rows
lstTitle.Items.Add(row("mTitle"))
Next
However, I must also mention that you really should also be using a parameter in your query rather than dynamically building the SQL statement like that, for instance:
myCmd.CommandText = "select mTitle from selectmovie where cName = #name"
myCmd.Parameters.AddWithValue("name", lstNames.SelectedItem)
To select all the movies where all of the multiple selected actors are involved, you would need to add an additional condition to your where clause for each actor, for instance:
Dim builder As New StringBuilder()
builder.Append("select distinct mTitle from selectmovie where ")
For i As Integer = 0 to lstNames.SelectedItems.Count - 1
Dim parameterName As String = "#name" & i.ToString()
If i <> 0 Then
builder.Append("and ")
End If
builder.Append(parameterName)
builder.Append(" in (select cName from selectmovie where mTitle = m.mTitle) ")
myCmd.Parameters.AddWithValue(parameterName, lstNames.SelectedItems(i))
Next
myCmd.CommandText = builder.ToString()