Empty row doing insert - vb.net

I have tried to enter a record with a new table and the below message shows:
"Input string was not in a correct format."
Here is my code:
Dim max_ As String = "select MAX(referance_number) from table"
Dim obj_ As New DATAAccess
Dim ds_ As New Data.DataSet
obj_.populate_dataset_Access_accdb_test(ds_, max_)
Dim ref As Integer = Convert.ToInt32(ds_.Tables(0).Rows(0).Item(0).ToString)
ref = ref + 1
Table columns are int with not null.

If the table is empty then the MAX will return NULL. That means your DataRow will contain DBNull.Value, whose ToString method returns String.Empty, which obviously can't be converted to an Integer. Test for NULL first using the DataRow's own IsNull method.
Of course, you could always do as many thousands of developers the world over do and let the database generated sequential IDs for you.

Related

Retrieve actual Table schema (excluding addtional table schema)In vb.net [duplicate]

When I run this code it is also retrieving some other fields which are not present in the table. How can I overcome this?
Dim conn As New OleDb.OleDbConnection
'Create a connection string for an Access database
Dim strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\check\a.mdb"
'Attach the connection string to the connection object
conn.ConnectionString = strConnectionString
'Open the connection
conn.Open()
Dim Restrictions() As String = {Nothing, Nothing, selected, Nothing}
Dim CollectionName As String = "Columns"
Dim dt As DataTable = conn.GetSchema(CollectionName, Restrictions)
For Each TableRow As DataRow In dt.Rows
ComboBox1.Items.Add(TableRow.Item("COLUMN_NAME"))
The additional columns which is also retrieved are:
1.ID
2.Date create
3.Date update
4.Id
5.Lv
6.Name
7.parent Id
8.Type
9.GUID
10.Id
... and 6 more. The original schema consists of only 5 fields.
Your problem is simply that the variable selected has the value Nothing when you insert it into the Restrictions() array. When I run the following code I only get the column names for the table named [new]:
Option Strict On
Imports System.Data.OleDb
Module Module1
Sub Main()
Dim connStr As String =
"Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=C:\Users\Public\test\so34490626\a.mdb"
Using conn As New OleDbConnection(connStr)
conn.Open()
Dim selected As String = "new"
Dim Restrictions() As String = {Nothing, Nothing, selected, Nothing}
Dim CollectionName As String = "Columns"
Dim dt As DataTable = conn.GetSchema(CollectionName, Restrictions)
For Each TableRow As DataRow In dt.Rows
Console.WriteLine(TableRow.Item("COLUMN_NAME"))
Next
End Using
End Sub
End Module
The result is:
GENDER
MEMBER OF RISHI PRASAD
NAME OF SADHAK
PROFESSION
However, when the value of selected is Nothing ...
Dim selected As String = Nothing
... I get the "extra" columns you describe
DateCreate
DateUpdate
Id
Lv
Name
ParentId
Type
Attributes
DataType
FieldName
IndexType
SkipColumn
SpecID
Start
Width
DateDelim
DateFourDigitYear
DateLeadingZeros
DateOrder
DecimalPoint
FieldSeparator
FileType
SpecID
SpecName
SpecType
StartRow
TextDelim
TimeDelim
GENDER
MEMBER OF RISHI PRASAD
NAME OF SADHAK
PROFESSION
The reason is revealed if I change the Console.WriteLine to include the table names:
Console.WriteLine("[{0}].[{1}]", TableRow.Item("TABLE_NAME"), TableRow.Item("COLUMN_NAME"))
Then we see:
[MSysAccessStorage].[DateCreate]
[MSysAccessStorage].[DateUpdate]
[MSysAccessStorage].[Id]
[MSysAccessStorage].[Lv]
[MSysAccessStorage].[Name]
[MSysAccessStorage].[ParentId]
[MSysAccessStorage].[Type]
[MSysIMEXColumns].[Attributes]
[MSysIMEXColumns].[DataType]
[MSysIMEXColumns].[FieldName]
[MSysIMEXColumns].[IndexType]
[MSysIMEXColumns].[SkipColumn]
[MSysIMEXColumns].[SpecID]
[MSysIMEXColumns].[Start]
[MSysIMEXColumns].[Width]
[MSysIMEXSpecs].[DateDelim]
[MSysIMEXSpecs].[DateFourDigitYear]
[MSysIMEXSpecs].[DateLeadingZeros]
[MSysIMEXSpecs].[DateOrder]
[MSysIMEXSpecs].[DecimalPoint]
[MSysIMEXSpecs].[FieldSeparator]
[MSysIMEXSpecs].[FileType]
[MSysIMEXSpecs].[SpecID]
[MSysIMEXSpecs].[SpecName]
[MSysIMEXSpecs].[SpecType]
[MSysIMEXSpecs].[StartRow]
[MSysIMEXSpecs].[TextDelim]
[MSysIMEXSpecs].[TimeDelim]
[new].[GENDER]
[new].[MEMBER OF RISHI PRASAD]
[new].[NAME OF SADHAK]
[new].[PROFESSION]
The "MSys*" tables are system tables that are hidden by default in the Access user interface.
Before looping on your table rows, you need to identify the valid/permanent columns of your dataTable.
To do so, you should first browse the columns collection of your datatable object. By checking the properties of each one of these columns, you will be able to identify the temporary ones. I guess it might be hidden somewhere in the 'extended properties' of the DataColumn object.
In order to identify the right property, you will go through something like this (written on the fly ...):
For each tableColumn as DataColumn in dt.Columns
Console.WriteLine(tableColumn.[propertyName].ToString())
...
Next
I do not know exactly which one of the properties will let you know if the column is part of the original table fields. You will have to guess and test in order to find it. Once it's identified, you then know how to select the rows to be added to your combobox.

get first row data from column from parameter tableadapter

I am trying to return the first row value on colunn rep-id. Here is what I have but is only working half way I am not getting my string value
Dim text as string = sdTableAdapter.Repds(endweek).Rows (0)
How do I get the first row string from my column
You can use the Field extension method, assuming it's the first column:
Dim table As DataTable = sdTableAdapter.Repds(endweek)
Dim text As String = table.Rows(0).Field(Of String)(0)
You can also use it via column-name:
Dim text As String = table.Rows(0).Field(Of String)("ColumnName")
You'll get an exception if the type is not String, then you need to convert it from the correct type(e.g. Int32):
Dim text As String = table.Rows(0).Field(Of Int32)("ColumnName").ToString()

Get SQL single value from query as String

I have the following code in my code behind:
Dim name As String
name.text= Staff.LoadName(StaffID)
The following query in my Class:
Public Function LoadName(ByVal ID As String)
Dim ds As New DataSet
Dim SQL As String = ""
SQL="select name from Staff where StaffID='" & ID & "' "
ds = Common.QueryDataByDataset(SQL)
ds.Tostring()
Return ds
End Function
But the name.Text doesn't show the value. How to I get the single value and convert it to string to display? Thanks
I am guessing the Common.QueryDataByDataset is from your library or some third party. Assuming it is executing the query and populating the dataset, you should be able to change the last two lines of the LoadName function to this:
String name = ds.Tables.Item("Staff").Rows(0)("name").ToString()
return name
You should add error handling in this method. For example, check to make sure the query returns exactly one result. Also, this method appears to be susceptible to SQL injection: http://en.wikipedia.org/wiki/SQL_injection

Find the maximum string in Combobox

I am trying to change combobox's DropDownWidth based on maximum string in Combobox's items.
The code below returns the maximum string length from all the items.
Dim maxStringLength As Integer = cboDt.AsEnumerable().
SelectMany(Function(row) row.ItemArray.OfType(Of String)()).
Max(Function(str) str.Length)
cboDt is the datatable attached to combobox.
I want to return the actual string.
For example if combobox items are:
"aaa"
"bbbb"
"ccccc"
My code returns maxStringLength = 5 (because 5 is the maximum number of characters of all items-here is ccccc)
I want code to retun "ccccc" (of course in a string variable)
Order the list by string-length descending, and then take the first result.
Dim maxStringLength As Integer =
cboDt.AsEnumerable().
SelectMany(Function(row) row.ItemArray.OfType(Of String)()).
OrderByDescending(Function(str) str.Length).
First() ' You can use FirstOrDefault here, if you are
' not certain there will be a result.
Assuming that the first column of the DataTable is displayed in the ComboBox:
Dim maxStringLength As Integer = cboDt.AsEnumerable().
Max(Function(r) r.Field(Of String)(0).Length)
Note that this assumes that this requires that this column is never null.
( I don't see a reason why you would measure the length of the (possibly available) other columns of the table when they aren't shown in the ComboBox at all. )
Update
Find the maximum string in Combobox
Now i got it, you want the string not the length:
Dim longestString = cboDt.AsEnumerable().
OrderByDescending(Function(r) r.Field(Of String)(0).Length).
First().Field(Of String)(0)
You can achieve this using linq and Finding the Index of maxStringLength = 5
Dim ls = comboBox4.Items.Cast(Of String)().ToList()
Dim index = ls.FindIndex(Function(c) c.ToString().Count() >= 5)
comboBox4.SelectedIndex = index
or using Max() Method
Dim ls = comboBox4.Items.Cast(Of String)().ToList()
Dim index = ls.Max()
comboBox4.Text = index

avoid checking for DataRow.IsDBNull on each column?

My code is 2x longer than it would be if I could automatically set IsDBNull to "" or simply roll over it without an error.
This is my code:
Dim conn As New SqlConnection
conn.ConnectionString = Module1.DBConn2
Dim sqlCommand = New SqlCommand("SELECT * FROM table", conn)
conn.Open()
Dim sqlDataset As DataSet = New DataSet()
Dim sqlDataAdapter As SqlDataAdapter = New SqlDataAdapter(sqlCommand)
sqlDataAdapter.Fill(sqlDataset)
conn.Close()
For Each rs As DataRow In sqlDataset.Tables(0).Rows
If Not IsDBNull(rs("column")) Then
Response.Write(rs("column"))
Else
Response.Write("")
End If
Response.Write("some stuff to write")
If Not IsDBNull(rs("column2")) Then
Response.Write(rs("column2"))
Else
Response.Write("")
End If
Next
In that case I'd just like to type Response.Write(rs("column")) instead of the If statement, and if column IsDBNull then output an empty string.
How can I do this?
Many thanks in advance!
You could simply use String.Join and pass row.ItemArray:
For Each row As DataRow In sqlDataset.Tables(0).Rows
Response.Write(String.Join("", row.ItemArray))
Next
That works since DBNull.ToString returns an empty string.
If you want to address every column, you can use the strongly typed DataRowExtensions.Field method which supports nullables and return null/Nothing for string. Then you could use the null-coalescing operator (?? in C#, If in VB).
Dim rowInfo = String.Format("{0}{1}{2}",
If(row.Field(Of String)("Column1"), ""),
If(row.Field(Of String)("Column2"), ""),
If(row.Field(Of String)("Column3"), ""))
However, note that String.Format will convert null/Nothing to "" implicitely anyway, so the If is redundant and just fyi.
MSDN:
If the object specified by index is a null reference (Nothing in
Visual Basic), then the format item is replaced by the empty string
("").
Here's a one-liner:
Response.Write(rs.IsNull("column") ? "" : rs("column"));
or make it an extension method:
public string GetValueOrBlankString(this DataRow rs, string column)
{
return rs.IsNull(column) ? "" : rs(column).ToString();
}
then call it as:
Response.Write(rs.GetValueOrBlankString("column"));
Dataset Extensions give you a clean way of doing and it's also strongly typed. The type must match the column type in the database though. If the database column can be null, then use a nullable type like below. The null values become Nothing for the returned nullable type.
For Each rs As DataRow In sqlDataset.Tables(0).Rows
'If string, you can use this. Null becomes nothing for the string.
Response.Write(rs.field(of String)("column"))
'if it's another type
Response.Write(rs.field(of Integer?)("column"))
Next
Ceres's answer is probably the best given that it avoids any sort of null testing, but it's worth noting that the 'IIF' function would also work pretty well her. It's still going to do the test for null but it's much more compact than how Joe was originally doing it. Something like this should do the trick:
For Each rs As DataRow In sqlDataset.Tables(0).Rows
Response.Write( IIF( IsDBNull(rs("column")), "", rs("column") ) )
Next
What's neat with this is you can substitute the "" for whatever you want to output if the value is in fact null ( a nice little added bonus. )
Here's some info on the 'IIF' function for those who don't know what it is:
http://msdn.microsoft.com/en-ca/library/27ydhh0d(v=vs.71).aspx