Split a string separated by a comma in jet sql access [duplicate] - ms-access
I m currently working on a SQl in MS-Access 2010 that can split a column based on a delimiter(,). In the column where I want to split on can have zero, one, two or three delimiter. I found out how i can split the column if there is only one delimiter (see SQL at the end of the question) but not if there are multiple delimiters.
The SQL is based on the following table. This table is filled with possible data that can occur in the table.
ID column_value
---------------------
1 2, 44
2 1
3 8, 9, 4
4 7
I want to split the column "value" in a way that i create a new table like this. It is not a problem that the column "ID" is the same because this will not be the PK.
ID value
---------------------
1 2
1 44
2 1
3 8
3 9
3 4
4 7
I tried to alter the SQL from this question but it only works when there is only 1 delimiter(,) due to the fact is uses the function LEFT and MID. I cant find how to alter it in a way that i can split if there are more then 1 delimiter in the column. The SQL i used to split if there is one delimiter:
select * into importeddata
from (SELECT column_value, id
FROM SourceData
WHERE InStr(column_value, ',') = 1
UNION ALL
SELECT Left(column_value, InStr(column_value, ',') - 1), id
FROM SourceData
WHERE InStr(column_value, ',') > 0
UNION ALL
SELECT mid(column_value, InStr(column_value, ',')+1 ), id
FROM SourceData
WHERE InStr(column_value, ',') > 0) AS CleanedUp;
Does somebody knows how to split a column if there is more then one delimiter?
To split and obtain a specific value, I prefer to use a user-defined function.
Public Function SplitString(str As String, delimiter As String, count As Integer) As String
Dim strArr() As String
strArr = Split(str, delimiter, count + 1)
count = count - 1 'zero-based
If UBound(strArr) >= count Then
SplitString = strArr(count)
End If
End Function
After this, you can adjust your SQL to the following:
SELECT * INTO importeddata
FROM (
SELECT SplitString(column_value, ',', 1), id
FROM SourceData
WHERE SplitString(column_value, ',', 1) <> ''
UNION ALL
SELECT SplitString(column_value, ',', 2), id
FROM SourceData
WHERE SplitString(column_value, ',', 2) <> ''
UNION ALL
SELECT SplitString(column_value, ',', 3), id
FROM SourceData
WHERE SplitString(column_value, ',', 3) <> ''
) AS A
If you really want an all-SQL solution, let me demonstrate to you how this can be achieved, and why this is a bad plan.
For this example, I've written the following code to automatically generate the appropriate SQL expression
Public Sub GenerateSQLSplit(str As String, Delimiter As String, Count As Integer)
Dim i As Integer
If Count = 1 Then
Debug.Print "IIf(InStr(1, " & str & ", " & Delimiter & ") = -1, " & str & ", Left(" & str & ", InStr(1, " & str & ", " & Delimiter & ") - 1))"
Else
Dim strPrevious As String
Dim strNext As String
strPrevious = "InStr(1, " & str & "," & Delimiter & ")"
i = Count - 1
Do While i <> 1
strPrevious = "InStr(" & strPrevious & " + Len(" & Delimiter & "), " & str & "," & Delimiter & ")"
i = i - 1
Loop
strNext = "InStr(" & strPrevious & " + Len(" & Delimiter & "), " & str & " , " & Delimiter & ")"
Debug.Print "IIf( " & strPrevious & "> 0, IIf(" & strNext & " < 1, Mid(" & str & ", " & strPrevious & " + Len(" & Delimiter & ")), Mid(" & str & ", " & strPrevious & " + Len(" & Delimiter & "), " & strNext & " - " & strPrevious & " - Len(" & Delimiter & "))), """") "
End If
End Sub
Let's use the example to generate a simple split: I want the 6th element of the following string: 1,2,3,4,5,6,7
To generate the string, in the immediate window:
GenerateSQLSplit "'1,2,3,4,5,6,7'", "','", 6
Results in the following expression to return the 6th element of that string (SQL only):
IIf( InStr(InStr(InStr(InStr(InStr(1, '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',')> 0, IIf(InStr(InStr(InStr(InStr(InStr(InStr(1, '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7' , ',') < 1, Mid('1,2,3,4,5,6,7', InStr(InStr(InStr(InStr(InStr(1, '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(',')), Mid('1,2,3,4,5,6,7', InStr(InStr(InStr(InStr(InStr(1, '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), InStr(InStr(InStr(InStr(InStr(InStr(1, '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7'
,',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7' , ',') - InStr(InStr(InStr(InStr(InStr(1, '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') + Len(','), '1,2,3,4,5,6,7',',') - Len(','))), "")
Append SELECT to the start of that, and execute it as a query, and it returns 6, as expected. Only you have a totally horrid query, while with the UDF you would just have SELECT SplitString("1,2,3,4,5,6,7", ",", 6)
You can, of course, use GenerateSQLSplit to create the query (I made sure it returned an empty string if the item was not in the string, so you can use that to test if an nth element exists). I do not recommend it, though, because the query will be long, inefficient and hard to maintain.
Related
IIF in microsoft report builder
I need to insert an IIF into the following expression in micorsoft report builder, and I keep getting an error. I want it to say if >1,1,"" =Round((Fields!percent_excellent.Value + Fields!percent_good.Value) * 100,0) & "% (" & Round(((Fields!percent_excellent.Value + Fields!percent_good.Value) - Fields!peer_group.Value) * 100,0) & "%)"
I don't know what you tried but this should work: =IIF(Round((Fields!percent_excellent.Value + Fields!percent_good.Value) * 100,0) > 1, 100, Round((Fields!percent_excellent.Value + Fields!percent_good.Value) * 100,0)) & "% (" & Round(((Fields!percent_excellent.Value + Fields!percent_good.Value) - Fields!peer_group.Value) * 100,0) & "%)" I think you'd be better using FORMATPERCENT to format your number with a set number of decimal places and adding the percent sign. =FORMATPERCENT( IIF( (Fields!percent_excellent.Value + Fields!percent_good.Value) * 100 > 1, 1, (Fields!percent_excellent.Value + Fields!percent_good.Value) * 100 ) , 0) & " (" FORMATPERCENT(((Fields!percent_excellent.Value + Fields!percent_good.Value) - Fields!peer_group.Value) * 100, 0) & ")"
Using SQL's DISTINCT function to remove unwanted duplicates with a custom delimiter?
I am trying to use GROUP_CONCAT with a custom delimiter which is working: private val mainQuery = "SELECT re.ENTRY_ID, " + "GROUP_CONCAT(re._ID, '§') AS read_id, " + "GROUP_CONCAT(re.READING_ELEMENT, '§') AS read_element, " + "GROUP_CONCAT(re.FURIGANA_BOTTOM, '§') AS furigana_bottom, " + "GROUP_CONCAT(re.FURIGANA_TOP, '§') AS furigana_top, " + "GROUP_CONCAT(re.NO_KANJI, '§') AS no_kanji, " + "GROUP_CONCAT(re.READING_COMMONNESS, '§') AS read_commonness, " + "GROUP_CONCAT(re.READING_RELATION, '§') AS read_rel, " + "GROUP_CONCAT(se.POS, '§') AS pos, " + "GROUP_CONCAT(se.GLOSS, '§') AS gloss, " + "GROUP_CONCAT(se.FIELD, '§') AS field, " + "GROUP_CONCAT(se.DIALECT, '§') AS dialect, " + "GROUP_CONCAT(se.INFORMATION, '§') AS info " + "FROM Jmdict_Reading_Element AS re " + "JOIN Jmdict_Sense_Element AS se ON re.ENTRY_ID = se.ENTRY_ID " + "JOIN Jmdict_Kanji_Element AS ke ON re.ENTRY_ID = ke.ENTRY_ID " private val kanjiQuery = mainQuery + "WHERE ke.ENTRY_ID IN (SELECT ENTRY_ID FROM Jmdict_Kanji_Element WHERE KANJI_ELEMENT LIKE ?) " + "GROUP BY re.ENTRY_ID " + "ORDER BY (CASE WHEN ke.KANJI_ELEMENT = ? THEN 1 ELSE 2 END), " + "(CASE WHEN ke.KANJI_ELEMENT LIKE ? THEN 1 ELSE 2 END), " + "(CASE WHEN se.GLOSS = ? THEN 1 ELSE 2 END), " + "(CASE WHEN se.GLOSS LIKE ? THEN 1 ELSE 2 END), re.READING_ELEMENT" private val kanaAndEnglishQuery = mainQuery + "WHERE re.ENTRY_ID IN (SELECT ENTRY_ID FROM Jmdict_Reading_Element WHERE READING_ELEMENT LIKE ?) " + "OR re.ENTRY_ID IN (SELECT ENTRY_ID FROM Jmdict_Sense_Element WHERE GLOSS LIKE ?) " + "GROUP BY re.ENTRY_ID " + "ORDER BY (CASE WHEN re.READING_ELEMENT = ? THEN 1 ELSE 2 END), " + "(CASE WHEN re.READING_ELEMENT LIKE ? THEN 1 ELSE 2 END), " + "(CASE WHEN se.GLOSS = ? THEN 1 ELSE 2 END), " + "(CASE WHEN se.GLOSS LIKE ? THEN 1 ELSE 2 END), re.READING_ELEMENT" However, as soon as I try to add DISTINCT: GROUP_CONCAT(DISTINCT re.READING_ELEMENT, '§') AS read_element, it no longer works: DISTINCT aggregates must have exactly one argument. I am trying to remove the duplicates found. (Even though they aren't in the database... if there is something that is in the query that is causing this please answer with that because that would also solve the problem)
SQLite does not support the separator argument if you use DISTINCT inside GROUP_CONCAT() (maybe it's a bug). What you can do is: REPLACE(GROUP_CONCAT(DISTINCT re.READING_ELEMENT), ',', '§') to replace all the commas (default delimiter) with the delimiter of your choice. If the column contains commas, then a (dirty) solution is to replace them with a character that you know does not exist, say '*': REPLACE(REPLACE(GROUP_CONCAT(DISTINCT REPLACE(re.READING_ELEMENT, ',', '*')), ',', '§'), '*', ',')
get the distinct() first using a subquery, before performing group_concat(). Since we will be getting distinct on re.READING_ELEMENT, will be grouping by this column instead. private val mainQuery = "SELECT re.ENTRY_ID, " + "GROUP_CONCAT(t1._ID, '§') AS read_id, " + "GROUP_CONCAT(t1.READING_ELEMENT, '§') AS read_element, " + "GROUP_CONCAT(t1.FURIGANA_BOTTOM, '§') AS furigana_bottom, " + "GROUP_CONCAT(t1.FURIGANA_TOP, '§') AS furigana_top, " + "GROUP_CONCAT(t1.NO_KANJI, '§') AS no_kanji, " + "GROUP_CONCAT(t1.READING_COMMONNESS, '§') AS read_commonness, " + "GROUP_CONCAT(t1.READING_RELATION, '§') AS read_rel, " + "GROUP_CONCAT(t1.POS, '§') AS pos, " + "GROUP_CONCAT(t1.GLOSS, '§') AS gloss, " + "GROUP_CONCAT(t1.FIELD, '§') AS field, " + "GROUP_CONCAT(t1.DIALECT, '§') AS dialect, " + "GROUP_CONCAT(t1.INFORMATION, '§') AS info FROM " + "(SELECT re._ID, re.READING_ELEMENT, re.FURIGANA_BOTTOM, re.FURIGANA_TOP, re.NO_KANJI " + ", re.READING_COMMONNESS, re.READING_RELATION, se.POS, se.GLOSS, se.FIELD, se.DIALECT, se.INFORMATION " + "FROM Jmdict_Reading_Element AS re " + "JOIN Jmdict_Sense_Element AS se ON re.ENTRY_ID = se.ENTRY_ID " + "JOIN Jmdict_Kanji_Element AS ke ON re.ENTRY_ID = ke.ENTRY_ID" private val kanjiQuery = mainQuery + " WHERE ke.ENTRY_ID IN (SELECT ENTRY_ID FROM Jmdict_Kanji_Element WHERE KANJI_ELEMENT LIKE ?) GROUP BY(re.READING_ELEMENT) ) t1" + "GROUP BY t1.ENTRY_ID " + "ORDER BY (CASE WHEN t1.KANJI_ELEMENT = ? THEN 1 ELSE 2 END), " + "(CASE WHEN t1.KANJI_ELEMENT LIKE ? THEN 1 ELSE 2 END), " + "(CASE WHEN t1.GLOSS = ? THEN 1 ELSE 2 END), " + "(CASE WHEN t1.GLOSS LIKE ? THEN 1 ELSE 2 END), t1.READING_ELEMENT" private val kanaAndEnglishQuery = mainQuery + " WHERE re.ENTRY_ID IN (SELECT ENTRY_ID FROM Jmdict_Reading_Element WHERE READING_ELEMENT LIKE ?) " + "OR re.ENTRY_ID IN (SELECT ENTRY_ID FROM Jmdict_Sense_Element WHERE GLOSS LIKE ?) GROUP BY(re.READING_ELEMENT)) t1" + "GROUP BY t1.ENTRY_ID" + "ORDER BY (CASE WHEN t1.READING_ELEMENT = ? THEN 1 ELSE 2 END), " + "(CASE WHEN t1.READING_ELEMENT LIKE ? THEN 1 ELSE 2 END), " + "(CASE WHEN t1.GLOSS = ? THEN 1 ELSE 2 END), " + "(CASE WHEN t1.GLOSS LIKE ? THEN 1 ELSE 2 END), t1.READING_ELEMENT"
How to Write this Crystal Report formula in SSRS Expression?
I am Having Problem to Convert this Crystal Report formula in SSRS Expression Can Anyone Help me? Formula 1: Dim fromExDay as String Dim toExDay as String Dim sYr as String Dim sMonth as String Dim sDay as String fromExDay = ToText({wk_TORIO0460_a.HktrExchngDayFrom}) fromExDay = Replace (fromExDay, ",", "" ) fromExDay = Replace (fromExDay, ".", "" ) toExDay = ToText({wk_TORIO0460_a.HktrExchngDayTo}) toExDay = Replace (toExDay, ",", "" ) toExDay = Replace (toExDay, ".", "" ) if Len (Trim(fromExDay)) > 0 and Len (Trim(toExDay)) > 0 then sYr = Right(Left(fromExDay, 4),2) if sYr <> "99" then sYr = LEFT(CStr(CDbl(sYr) + 12),2) end if sMonth = Mid(fromExDay, 5, 2) sDay = Left(Right(fromExDay, 4),2) 'fromExDay = sYr + sMonth + sDay fromExDay = sYr + sMonth + sDay sYr = Right(Left(toExDay, 4),2) if sYr <> "99" then sYr = LEFT(CStr(CDbl(sYr) + 12),2) end if sMonth = Mid(toExDay, 5, 2) sDay = Left(Right(toExDay, 4),2) toExDay = sYr + sMonth + sDay 'toExDay = Right(fromExDay, 2) Formula = fromExDay + " ~ " + toExDay Else Formula = "" End If Value of ExchangeFrom and ExchangeTO is coming from Database . ExchangeFrom value = 20031031 ExchangeTo value = 200 Is There in Database
Is the return value supposed to be 151010 ~ 1220 There actually weren't many changes needed to convert it to an SSRS VB function. In SSRS, the function doesn't work directly with the field so you need to pass them to the function as parameters. Most of the rest of the VB in your old function should work the same in SSRS - I just removed the ToText functions that aren't in SSRS. When you call the function from your text box, you pass the fields. =code.Formula1(Fields!HktrExchngDayFrom.Value, Fields!HktrExchngDayTo.Value) And here's the function: Public Function Formula1(ByVal fromExDay as String, ByVal toExDay as String) as String Dim sYr as String Dim sMonth as String Dim sDay as String fromExDay = Replace (fromExDay, ",", "" ) fromExDay = Replace (fromExDay, ".", "" ) toExDay = Replace (toExDay, ",", "" ) toExDay = Replace (toExDay, ".", "" ) if Len (Trim(fromExDay)) > 0 and Len (Trim(toExDay)) > 0 then sYr = Right(Left(fromExDay, 4),2) if sYr <> "99" then sYr = LEFT(CStr(CDbl(sYr) + 12), 2) end if sMonth = Mid(fromExDay, 5, 2) sDay = Left(Right(fromExDay, 4), 2) fromExDay = sYr + sMonth + sDay sYr = Right(Left(toExDay, 4), 2) if sYr <> "99" then sYr = LEFT(CStr(CDbl(sYr) + 12), 2) end if sMonth = Mid(toExDay, 5, 2) sDay = Left(Right(toExDay, 4), 2) toExDay = sYr + sMonth + sDay Formula1 = fromExDay + " ~ " + toExDay Else Formula1 = "" End If End Function I think the sDay calculations are incorrect. sDay = Left(Right(fromExDay, 4),2) Seems to be getting the month again. It should probably be sDay = Right(fromExDay, 2) or, if it can be a longer string use MID: sDay = Mid(fromExDay, 7, 2) Which changes the result to: 151031 ~ 12
For making this Formula I Taken Two Textbox in Active Report page and I divided this formula Into two Parts. Textbox1: =iif(Right(Left( Fields!ExchngDayFrom.Value , 4),2) <> 99 ,LEFT(CStr(CDbl((Right(Left( Fields!ExchngDayFrom.Value , 4),2) ) + 12),2) + Mid( Fields!ExchngDayFrom.Value , 5, 2) + Left(Right( Fields!ExchngDayFrom.Value , 2),2 ) ," ") Assuming Value of ExchangeDayfrom is : 20031031 Output is 151031 TextBox2: ="~ " & iif(Right(Left( Fields!ExchngDayTo.Value , 4),2) <> 99 ,LEFT(CStr(CDbl((Right(Left( Fields!ExchngDayTo.Value , 4),2)) + 12),2) + Mid( Fields!ExchngDayTo.Value , 5, 2) + Left(Right( Fields!ExchngDayTo.Value , 2),2 ) , Right(Left( Fields!ExchngDayTo.Value , 4),2) + Mid( Fields!ExchngDayTo.Value , 5, 2) + Left(Right( Fields!ExchngDayTo.Value , 2),2 ) Assuming Value of ExchangeDayTo is : 99999999 Output is ~ 999999 This is How I Solve my Problem.Big thanks to #Hannover Fist sir thanks Your valuable Solution and Yes Your Solution is Right it's also worked Perfectly
How can I search whole word not partial match in string in VBA
I am trying to replace a word in a string. The below code does the replacing job, but it also replaces partial match which I don't want it to do. If InStr(inputString, "North") Then inputString = Replace(inputString, "North", "N") End If This code replaces north with N, which is great, but it also replaces Northern with Nern, which I don't want. How can I compare only the whole word? In php it's == but I am not sure in VBA, by the way I am using this in MS Access VBA.
you could go like this If InStr(inputString, "North") Then inputString = Trim(Replace(Replace(Replace(inputString & " ", " North ", " North "), " North ", " N"), " ", " ")) which is the "contraction" of If InStr(inputString, "North") Then inputString = inputString & " " '<-- add a space at the end to catch "North" should it be the last "word" in a possible "...North" string inputString = Replace(inputString, " North ", " North ") '<-- double spaces before and after any " North " occurrence, necessary for subsequent statement to properly work should there be more than one " North " occurrence inputString = Replace(inputString, " North ", " N") '<-- make the "core" replacement inputString = Replace(Replace(inputString, " North ", " N"), " ", " ") '<-- make all double spaces occurrences as single ones End If
Here is a solution to what you asked Public Function WordMatch(ByVal Text As String, ByVal Word As String) As Boolean Dim RightChar As String Dim LeftChar As String Dim IStart As Integer Dim IEnd As Integer Dim Flag As Boolean Dim Alphabet As String Alphabet = "abcdefghijklmnopqrstuvwxyz" Flag = True IStart = InStr(Text, Word) If Not (IStart > 0) Then Flag = False Else IEnd = IStart + Len(Word) - 1 If (IStart = 1 And IEnd = 1) Then GoTo WordMatched If IStart > 1 Then LeftChar = Mid(Text, IStart - 1, 1) 'LeftChar = Mid(Text, IStart - 1 - 3, 4) 'MsgBox "L'" & LeftChar & "' - " & Text & " - " & Word If InStr(Alphabet, LeftChar) > 0 Then Flag = False End If End If If (IEnd < Len(Text)) Then RightChar = Mid(Text, IEnd + 1, 1) 'RightChar = Mid(Text, IEnd + 1, 4) 'MsgBox "R'" & RightChar & "' - " & Text & " - " & Word If InStr(Alphabet, RightChar) > 0 Then Flag = False End If End If 'End If End If WordMatched: WordMatch = Flag End Function
How to fix DataGridView Error: Is it possible that my null field result in MySQL query is the cause?
I was trying to show my query result using a datagridview when i bumped into these errors... The following exception occurred in the DataGridView: System.ArgumentException: Parameter is not valid. at System.Drawing.IMage.FromStream(Stream stream, BooleanuseEmbeddedColorManagement, Boolean validateImageData) at System.Drawing.ImageConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) at System.Windows.Forms.Formatter.FormatObjectInternal(Objectvalue, Type targetTyep, TypeConverter sourceConverter, TypeConverter targetConverter, String formatString, IFormatProvider formatInfo, Object formattedNullValue) at System.Windows.Forms.Formatter.FormatObject(Object value, Type targetType, TypeConverter sourceConverter, TypeConverter targetConverter, String formatString, IFormatProvider formatInfo, Object formattedNullValue, Object dataSourceNullValue) at System.Window.Forms.DataGridViewCell.GetFormattedValue(Object value, Int32 rowIndex, DataGridViewCellStyle& cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) To replace this default dialog please handle the DataError event. Well, I do get something like 8 dialogs like this when I use the datagridview, however, when I run a line-by-line checking using a breakpoint, I don't get prompted for a single error! I think it's this datagridview. I already tried to delete the datagridview and just put a new one but the same problem exists. for your reference, here is the code I use in putting data into my datagridview: Public Sub fillDGVBulk() Try Dim bulkCmd As New MySqlCommand("select * from " _ + "( " _ + " select controlno, bulk.catid, bulk.bcode, " _ + " ( " _ + " bulk.itemqty " _ + " ) as stock, " _ + " case when resv.qty is null then " _ + " '0' else resv.qty end as booked, " _ + " case when " _ + " ( " _ + " bulk.itemqty-sumqty " _ + " ) is null then " _ + " bulk.itemqty else (bulk.itemqty-sumqty) end as available, bulk.itemname, bulk.deptcode, bulk.loccode, resv.resdate, resv.timestart, resv.timeend " _ + " from tbl_items_bulk bulk " _ + " left join " _ + " ( " _ + " select rs.controlno, rs.bcode, rs.qty, sum(rs.qty) as sumqty, rs.resdate, rs.timestart, rs.timeend " _ + " from tbl_reservations rs " _ + " where retdate is null " _ + " and restype='1' " _ + " and resdate = #date " _ + " and not " _ + " ( " _ + " (timestart between #tStart and #tEnd) or " _ + " (timeend between #tStart and #tEnd) or " _ + " (timestart <= #tStart and timeend >= #tEnd) " _ + " ) " _ + " or rs.bcode is null " _ + " and (claimdate is null and retdate is null) " _ + " group by bcode " _ + " ) resv " _ + " on bulk.bcode=resv.bcode " _ + " where ((bulk.itemqty-sumqty) >= 1) or (bulk.itemqty-sumqty) is null " _ + " order by resdate, timestart " _ + ") rvs " _ + "where rvs.catid=#catid " _ + "order by controlno", conn) With bulkCmd .Parameters.AddWithValue("#catid", cbo_catbulk.SelectedValue.ToString) .Parameters.AddWithValue("#date", dtp_datebulk.Value.ToString) .Parameters.AddWithValue("#tStart", cbo_startbulk.SelectedValue.ToString) .Parameters.AddWithValue("#tEnd", cbo_endbulk.SelectedValue.ToString) End With Dim DAdapter2 As New MySqlDataAdapter() DAdapter2.SelectCommand = bulkCmd If conn.State = ConnectionState.Open Then conn.Close() conn.Open() Else conn.Open() End If Dim table2 As New DataTable DAdapter2.Fill(table2) DataGridView2.DataSource = table2 conn.Close() 'controlno, catid, bcode, stock, booked, available, resdate, timestart, timeend With DataGridView2 .Columns(0).Visible = False .Columns(1).HeaderText = "Category ID" .Columns(2).HeaderText = "Barcode" .Columns(3).HeaderText = "Stock" .Columns(4).HeaderText = "Booked" .Columns(5).HeaderText = "Available" ' .Columns(5).DefaultCellStyle.BackColor = Color.LightGreen .Columns(6).HeaderText = "Item" .Columns(7).HeaderText = "Department" .Columns(8).HeaderText = "Storage Area" .Columns(9).Visible = False .Columns(10).Visible = False .Columns(11).Visible = False End With Catch ex As Exception MsgBox(ex.Message.ToString + " Error No: " + Err.Number.ToString) End Try End Sub Can anybody help me out? Thanks in advance! :)
I'm trying a wild guess here.. During runtime, while this code sets table2 as the dataSource of the DataGridView, DataGridView2.DataSource = table2 these codes immediately runs... With DataGridView2 .Columns(0).Visible = False .Columns(1).HeaderText = "Category ID" .Columns(2).HeaderText = "Barcode" .Columns(3).HeaderText = "Stock" .Columns(4).HeaderText = "Booked" .Columns(5).HeaderText = "Available" ' .Columns(5).DefaultCellStyle.BackColor = Color.LightGreen .Columns(6).HeaderText = "Item" .Columns(7).HeaderText = "Department" .Columns(8).HeaderText = "Storage Area" .Columns(9).Visible = False .Columns(10).Visible = False .Columns(11).Visible = False End With Which will rename/hides the columns. Rather renaming the DataGridView2's column header texts, which I think causes the runtime error, because it doesn't yet have the columns of the result set. Why not use the AS keyword on the SELECT statement, so that you can rename the column names of the result set of your query. Try this on your initial select statement.. Dim bulkCmd As New MySqlCommand("select catid AS `Category ID`, bcode AS `Barcode`, stock AS Stock, booked AS `Booked`, available AS `Available`, resdate AS `Item`, timestart AS `Department`, timeend AS `Storage Area` from " _