Search Results

Search found 30 results on 2 pages for 'oledbdatareader'.

Page 1/2 | 1 2  | Next Page >

  • Converting Byte[] to String - Interbase to C# - InvalidCastException

    - by NorthernOutpost
    I'm using OleDbDataReader rdr to read a "Comments" field in BLOB form (sub_type 1 segment size 80) into a string from an Interbase DB, and I keep getting exceptions. Any suggestions? Attempt #1 ls_Chap_Comments.Add((rdr["Comments"]).ToString()); InvalidCastException: The data value could not be converted for reasons other than sign mismatch or data overflow. For example, the data was corrupted in the data store but the row was still retrievable." Attempt #2 byte[] b = new byte[100]; b = (byte[])rdr["Comments"]; string s = System.Text.ASCIIEncoding.ASCII.GetString(b); InvalidCastException: Unable to cast object of type System.String to type System.Byte[] Attempt #3 // 17 is the BLOB column zero-based location for "Comments" retval = rdr.GetBytes(17, startIndex, outbyte, 0, bufferSize); InvalidCastException: Unable to cast object of type System.String to type System.Byte[]. Any suggestions would be really appreciated!

    Read the article

  • How to force ADO.Net to use only the System.String DataType in the readers TableSchema.

    - by Keith Sirmons
    Howdy, I am using an OleDbConnection to query an Excel 2007 Spreadsheet. I want force the OleDbDataReader to use only string as the column datatype. The system is looking at the first 8 rows of data and inferring the data type to be Double. The problem is that on row 9 I have a string in that column and the OleDbDataReader is returning a Null value since it could not be cast to a Double. I have used these connection strings: Provider=Microsoft.ACE.OLEDB.12.0;Data Source="ExcelFile.xlsx";Persist Security Info=False;Extended Properties="Excel 12.0;IMEX=1;HDR=No" Provider=Microsoft.Jet.OLEDB.4.0;Data Source="ExcelFile.xlsx";Persist Security Info=False;Extended Properties="Excel 8.0;HDR=No;IMEX=1" Looking at the reader.GetSchemaTable().Rows[7].ItemArray[5], it's dataType is Double. Row 7 in this schema correlates with the specific column in Excel I am having issues with. ItemArray[5] is its DataType column Is it possible to create a custom TableSchema for the reader so when accessing the ExcelFiles, I can treat all cells as text instead of letting the system attempt to infer the datatype? I found some good info at this page: Tips for reading Excel spreadsheets using ADO.NET The main quirk about the ADO.NET interface is how datatypes are handled. (You'll notice I've been carefully avoiding the question of which datatypes are returned when reading the spreadsheet.) Are you ready for this? ADO.NET scans the first 8 rows of data, and based on that guesses the datatype for each column. Then it attempts to coerce all data from that column to that datatype, returning NULL whenever the coercion fails! Thank you, Keith Here is a reduced version of my code: using (OleDbConnection connection = new OleDbConnection(BuildConnectionString(dataMapper).ToString())) { connection.Open(); using (OleDbCommand cmd = new OleDbCommand()) { cmd.Connection = connection; cmd.CommandText = SELECT * from [Sheet1$]; using (OleDbDataReader reader = cmd.ExecuteReader()) { using (DataTable dataTable = new DataTable("TestTable")) { dataTable.Load(reader); base.SourceDataSet.Tables.Add(dataTable); } } } }

    Read the article

  • problem with DataReader ASP.NET (Visual Basic)

    - by ZiGi
    Hey, I have this problem : [InvalidOperationException: No data exists for the row / column.] System.Data.OleDb.OleDbDataReader.DoValueCheck(Int32 ordinal) +1029063 System.Data.OleDb.OleDbDataReader.GetInt32(Int32 ordinal) +12 ASP.addsousvoyage_aspx.hdVoyage_SelectedIndexChanged(Object sender, EventArgs e) in C:\Users\ZiGi\Desktop\VisualDesign\addSousVoyage.aspx:222 System.Web.UI.WebControls.ListControl.OnSelectedIndexChanged(EventArgs e) +111 System.Web.UI.WebControls.DropDownList.RaisePostDataChangedEvent() +134 System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent() +10 System.Web.UI.Page.RaiseChangedEvents() +165 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1485 When I do this : MsgBox(myReader1.GetInt32(0).ToString) Even if : MsgBox(myReader1.FieldCount) returning 1 as value and the field(0) is integer. What's the problem ?

    Read the article

  • How can I read a DBF file with incorrectly defined column data types using ADO.NET?

    - by Jason
    I have a several DBF files generated by a third party that I need to be able to query. I am having trouble because all of the column types have been defined as characters, but the data within some of these fields actually contain binary data. If I try to read these fields using an OleDbDataReader as anything other than a string or character array, I get an InvalidCastException thrown, but I need to be able to read them as a binary value or at least cast/convert them after they are read. The columns that actually DO contain text are being returned as expected. For example, the very first column is defined as a character field with a length of 2 bytes, but the field contains a 16-bit integer. I have written the following test code to read the first column and convert it to the appropriate data type, but the value is not coming out right. The first row of the database has a value of 17365 (0x43D5) in the first column. Running the following code, what I end up getting is 17215 (0x433F). I'm pretty sure it has to do with using the ASCII encoding to get the bytes from the string returned by the data reader, but I'm not sure of another way to get the value into the format that I need, other that to write my own DBF reader and bypass ADO.NET altogether which I don't want to do unless I absolutely have to. Any help would be greatly appreciated. byte[] c0; int i0; string con = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\ASTM;Extended Properties=dBASE III;User ID=Admin;Password=;"; using (OleDbConnection c = new OleDbConnection(con)) { c.Open(); OleDbCommand cmd = c.CreateCommand(); cmd.CommandText = "SELECT * FROM astm2007"; OleDbDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { c0 = Encoding.ASCII.GetBytes(dr.GetValue(0).ToString()); i0 = BitConverter.ToInt16(c0, 0); } dr.Dispose(); }

    Read the article

  • help date format in vb.net

    - by bachchan
    Dim Con As OleDb.OleDbConnection Dim Sql As String = Nothing Dim Reader As OleDb.OleDbDataReader Dim ComboRow As Integer = -1 Dim Columns As Integer = 0 Dim Category As String = Nothing Dim oDatumMin As Date Dim column As String column = Replace(TxtDateMax.Text, "'", "''") 'oDatumMin = Convert.ToDateTime(TxtDateMin.Text) oDatumMin = DtpMin.Value Dim oPath As String oPath = Application.StartupPath ' Select records. Con = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & oPath & "\trb.accdb;") Dim cmd As New OleDb.OleDbCommand 'Dim data_reader As OleDbDataReader = cmd.ExecuteReader() Sql = ("SELECT * FROM " & cmbvalue & " WHERE Datum>='" & oDatumMin & "'") cmd = New OleDb.OleDbCommand(Sql, Con) Con.Open() Reader = cmd.ExecuteReader() Do While Reader.Read() Dim new_item As New ListViewItem(Reader.Item("Datum").ToString) new_item.SubItems.Add(Reader.Item("Steleks i krpe za cišcenje-toal papir-ubrusi-domestos").ToString) new_item.SubItems.Add(Reader.Item("TEKUCINA ZA CIŠCENJE PLOCICA").ToString) new_item.SubItems.Add(Reader.Item("KESE ZA SMECE").ToString) new_item.SubItems.Add(Reader.Item("OSTALO-džoger-spužva za laminat").ToString) new_item.SubItems.Add(Reader.Item("PAPIR").ToString) LvIzvjestaj.Items.Add(new_item) Loop ' Close the connection.strong text Con.Close()`` when i select table,(cmbvalue) from combobox and when i select date from datetime picker (dtp) or in last case from texbox converted to date and time sql looks like this "SELECT * FROM Uprava WHERE Datum='2.6.2010 10:28:14'" and all query looks ok but am geting Data type mismatch in criteria expression. error for date (oDatumMin) when excute column in access is also set to date i have no idea what else to try

    Read the article

  • OleDB Jet - Float issues in reading excel data

    - by Patrick
    When I read a sheet into a DataTable using the OleDbDataReader, floating point numbers loose their precision. I tried forcing OleDb to read the excel data as string, but although the data is now contained in a DataRow with each Column defined as System.String it looses precision (18.125 - 18.124962832). Any idea how to avoid this behaviour?

    Read the article

  • Problem with continue in While Loop within Try/Catch in C# (2.0)

    - by csharpnoob
    Hi, when i try to use in my ASPX Webpage in the Code Behind this try{ while() { ... db.Open(); readDataMoney = new OleDbCommand("SELECT * FROM Customer WHERE card = '" + customer.card + "';", db).ExecuteReader(); while (readDataMoney.Read()) { try { if (!readDataMoney.IsDBNull(readDataMoney.GetOrdinal("Credit"))) { customer.credit = Convert.ToDouble(readDataMoney[readDataMoney.GetOrdinal("Credit")]); } if (!readDataMoney.IsDBNull(readDataMoney.GetOrdinal("Bonus"))) { customer.bonus = Convert.ToDouble(readDataMoney[readDataMoney.GetOrdinal("Bonus")]); } } catch (Exception ex) { Connector.writeLog("Money: " + ex.StackTrace + "" + ex.Message + "" + ex.Source); customer.credit = 0.0; customer.credit = 0.0; continue; } finally { } } readDataMoney.Close(); vsiDB.Close(); ... } }catch { continue; } The whole page hangs if there is a problem when the read from db isn't working. I tried to check for !isNull, but same problem. I have a lots of differend MDB Files to process, which are readonly (can't repair/compact) and some or others not. Same Design/Layout of Tables. With good old ASP Classic 3.0 all of them are processing with the "On Resume Next". I know I know. But that's how it is. Can't change the source. So the basic question: So is there any way to tell .NET to continue the loop whatever happens within the try loop if there is any exception? After a lots of wating time i get this exceptions: at System.Data.Common.UnsafeNativeMethods.IDBInitializeInitialize.Invoke(IntPtr pThis) at System.Data.OleDb.DataSourceWrapper.InitializeAndCreateSession(OleDbConnectionString constr, SessionWrapper& sessionWrapper) at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.OleDb.OleDbConnection.Open() at GetCustomer(String card)Thread was being aborted.System.Data and System.Runtime.InteropServices.Marshal.ReadInt16(IntPtr ptr, Int32 ofs) System.Data.ProviderBase.DbBuffer.ReadInt16(Int32 offset) System.Data.OleDb.ColumnBinding.Value_I2() System.Data.OleDb.ColumnBinding.Value() System.Data.OleDb.OleDbDataReader.GetValue(Int32 ordinal) System.Data.OleDb.OleDbDataReader.get_Item(Int32 index) Thread was terminated.mscorlib Thanks for any help.

    Read the article

  • C# Object Problem - Can't Solve It

    - by user612041
    I'm getting the error 'Object reference not set to an instance of an object'. I've tried looking at similar problems but genuinely cannot see what the problem is with my program. The line of code that I am having an error with is: labelQuestion.Text = table.Rows[0]["Question"].ToString(); Here is my code in its entirety: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; using System.Data.Sql; using System.Data.SqlClient; namespace Quiz_Test { public partial class Form1 : Form { public Form1() { InitializeComponent(); } String chosenAnswer, correctAnswer; DataTable table; private void Form1_Load(object sender, EventArgs e) { //declare connection string using windows security string cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\QuizQuestions.accdb"; //declare Connection, command and other related objects OleDbConnection conGet = new OleDbConnection(cnString); OleDbCommand cmdGet = new OleDbCommand(); //try //{ //open connection conGet.Open(); //String correctAnswer; cmdGet.CommandType = CommandType.Text; cmdGet.Connection = conGet; cmdGet.CommandText = "SELECT * FROM QuizQuestions ORDER BY rnd()"; OleDbDataReader reader = cmdGet.ExecuteReader(); reader.Read(); labelQuestion.Text = table.Rows[0]["Question"].ToString(); radioButton1.Text = table.Rows[0]["Answer 1"].ToString(); radioButton2.Text = table.Rows[0]["Answer 2"].ToString(); radioButton3.Text = table.Rows[0]["Answer 3"].ToString(); radioButton4.Text = table.Rows[0]["Answer 4"].ToString(); correctAnswer = table.Rows[0]["Correct Answer"].ToString(); ; conGet.Close(); } private void btnSelect_Click(object sender, EventArgs e) { String cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\QuizQuestions.accdb"; //declare Connection, command and other related objects OleDbConnection conGet = new OleDbConnection(cnString); OleDbCommand cmdGet = new OleDbCommand(); //try { //open connection conGet.Open(); cmdGet.CommandType = CommandType.Text; cmdGet.Connection = conGet; cmdGet.CommandText = "SELECT * FROM QuizQuestions ORDER BY rnd()"; // select all columns in all rows OleDbDataReader reader = cmdGet.ExecuteReader(); reader.Read(); if (radioButton1.Checked) { chosenAnswer = reader["Answer 1"].ToString(); } else if (radioButton2.Checked) { chosenAnswer = reader["Answer 2"].ToString(); } else if (radioButton3.Checked) { chosenAnswer = reader["Answer 3"].ToString(); } else { chosenAnswer = reader["Answer 4"].ToString(); } if (chosenAnswer == reader["Correct Answer"].ToString()) { //chosenCorrectly++; MessageBox.Show("You have got this answer correct"); //label2.Text = "You have got " + chosenCorrectly + " answers correct"; } else { MessageBox.Show("That is not the correct answer"); } } } } } I realise the problem isn't too big but I can't see how my declaration timings are wrong

    Read the article

  • Active directory select and display with asp.net (oledb) (error code: DB_E_ERRORSINCOMMAND(0x80040E1

    - by Phil
    I am trying to make a page which displays some user information returned from active directory. Here is my code so far: Dim oConnection As OleDbConnection Dim oCmd As OleDbCommand Dim strADOQuery As String Dim oleReader As OleDbDataReader oConnection = New OleDbConnection() oCmd = New OleDbCommand() oConnection.ConnectionString = "Provider=ADsDSOObject;" oConnection.Open() oCmd.Connection = oConnection strADOQuery = "select distinguishedName, cn, givenname, sn, mail, middleName, displayName, description, telephonenumber, physicalDeliveryOfficeName, employeeID from 'LDAP://dc=foo,dc=ac,dc=uk' WHERE objectCategory='Person' AND objectClass='user' AND sAMAccountName='" & Uname & "'""" oCmd.CommandText = strADOQuery oCmd.CommandTimeout = 600 oCmd.ExecuteReader() While oleReader.Read ADDN = r("distinguishedName") ADCommonName = r("cn") ADFirstName = r("givenname") ADLastName = r("sn") ADEmail = r("mail") ADFirstandLast = r("displayName") ADDescription = r("description") ADTelephone = r("telephonenumber") ADOffice = r("physicalDeliveryOfficeName") ADStaffnum = r("employeeID") End While oConnection.Close() oleReader.Close() I'm finding it hard to see exactly what is wrong with the code. The error message presented is vague: 'ADsDSOObject' failed with no error message available, result code: DB_E_ERRORSINCOMMAND(0x80040E14). Any assistance would be greatly appreciated Thanks.

    Read the article

  • How to read a CLOB column in Oracle using OleDb ?

    - by T.Falise
    Hi, I have created a table on an Oracle 10g database with this structure : create table myTable ( id number(32,0) primary key, myData clob ) I can insert rows in the table without any problem, but when I try to read data from the table using OleDb connection, I get an exception. Here is the code I use : using (OleDbConnection dbConnection = new OleDbConnection("ConnectionString")) { dbConnection.Open(); OleDbCommand dbCommand = dbConnection.CreateCommand(); dbCommand.CommandText = "SELECT * FROM myTable WHERE id=?"; dbCommand.Parameters.AddWithValue("ID", id); OleDbDataReader dbReader = dbCommand.ExecuteReader(); } The exception details seems to point on an unsupported data type : System.Data.OleDb.OleDbException: Unspecified error Oracle error occurred, but error message could not be retrieved from Oracle. Data type is not supported. Does anyone know how I can read this data using the OleDb connection ? PS : The driver used in this case is the Microsoft one.

    Read the article

  • Print ms access data in vb.net

    - by user225269
    How do I print the ms access data(.mdb) in vb.net? Here is the code that I'm using to view the data in the form. What I want to do is to be able to print what is currently being viewed. Perhaps automatically save the .pdf file and the pdf viewer installed on the system will open that newly generated pdf file Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\search.mdb") Dim cmd As OleDbCommand = New OleDbCommand("Select * from GH where NAME= '" & TextBox6.Text & "' ", cn) cn.Open() Dim rdr As OleDbDataReader rdr = cmd.ExecuteReader If rdr.HasRows Then rdr.Read() NoAcc = rdr("NAME") If (TextBox6.Text = NoAcc) Then TextBox1.Text = rdr("IDNUMBER") If (TextBox6.Text = NoAcc) Then TextBox7.Text = rdr("DEPARTMENT") If (TextBox6.Text = NoAcc) Then TextBox8.Text = rdr("COURSE") End If -some sites for beginners regarding this topic would help a lot:)

    Read the article

  • Excel - referenced values via OleDB from .Net client

    - by ho
    I'm trying to read an Excel file (.xls, I think Excel 2003 compatible) via OleDB, but it fails to get the values for referenced fields. This is my current test code (please note, this is just part of the class): Private m_conn As OleDbConnection Public Sub New(ByVal fileName As String) Dim connString As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;", fileName) m_conn = New OleDbConnection(connString) m_conn.Open() End Sub Public Sub GetSheet(ByVal sheet As String) Dim query As String = String.Format("SELECT * FROM [{0}]", sheet) Using cmd As OleDbCommand = m_conn.CreateCommand() cmd.CommandText = query Dim ds As New DataSet() Dim a As New OleDbDataAdapter(cmd) Using rdr As OleDbDataReader = cmd.ExecuteReader() While rdr.Read() Debug.WriteLine(rdr.Item(0).ToString()) End While End Using End Using End Sub But if the value is a reference (something like =+'MySheetName'!K37), I just get a DBNull from the call to rdr.Item(0). I can get around this by automating Excel instead, but would prefer not to have to use Excel automation so wondering if anyone knows how to do it.

    Read the article

  • Importing a spreadsheet, but having trouble.

    - by Chris Phelps
    I have a form that allows a user to import a spreadsheet. This spreadsheet is generally static when it comes to column headers, but now the users want to be able to include an optional column (called Notes). My code crashes when I try to read the column from the spreadsheet if it doesn't exist. Dim objCommand As New OleDbCommand() objCommand = ExcelConnection() 'function that opens spreadsheet and returns objCommand Dim reader As OleDbDataReader reader = objCommand.ExecuteReader() While reader.Read() Dim Employee As String = Convert.ToString(reader("User")) Dim SerialNUM As String = Convert.ToString(reader("serialno")) **Dim Notes As String = Convert.ToString(reader("notes"))** If the spreadsheet contains a Notes column, all goes well. If not, crash. How can I check to see if the Notes column exists in the spreadsheet to avoid the crash?

    Read the article

  • How to convert ms access data into pdf in vb.net

    - by user225269
    I want to convert the ms access data into a document so that the print function in vb.net will read it. Where do I start from here? Here is my form: http://screencast.com/t/MGU4N2UyNmY And here is the code for print preview. Try PrintPreviewDialog1.ShowDialog() Catch es As Exception MessageBox.Show(es.Message) End Try How do I incorporate the above code, to the code below so that there is something that can be seen when I hit the print button? Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\search.mdb") Dim cmd As OleDbCommand = New OleDbCommand("Select * from GH where NAME= '" & TextBox6.Text & "' ", cn) cn.Open() Dim rdr As OleDbDataReader rdr = cmd.ExecuteReader If rdr.HasRows Then rdr.Read() NoAcc = rdr("NAME") If (TextBox6.Text = NoAcc) Then TextBox1.Text = rdr("IDNUMBER") If (TextBox6.Text = NoAcc) Then TextBox7.Text = rdr("DEPARTMENT") If (TextBox6.Text = NoAcc) Then TextBox8.Text = rdr("COURSE") End If Please help,thanks

    Read the article

  • How to read and loop through each rows in an Excel using C#

    - by Ullan
    I need to read an excel file and loop through the rows. I used the below code to read the excel file. But I am not getting the entire row, inseatd of getting the column values. try { OleDbConnection objConnection = new OleDbConnection(strConnectionString); string queryString = string.Format("Select * from [{0}$]", strSheetName, objConnection); OleDbCommand command = new OleDbCommand(queryString, objConnection); objConnection.Open(); OleDbDataReader reader = command.ExecuteReader(); while (reader.Read()) { var val1 = reader[0].ToString(); //Here I want to get each row } reader.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } I need to check if the row is empty or not, if not empty, I need to serach for some values in a particular column. Thanks for your help

    Read the article

  • How to pass a value from a method to property procedure in c#?

    - by sameer
    Here is my code: The jewellery class is my main class in which i am inheriting a connection string class. class Jewellery : Connectionstr { string lmcode; public string LM_code/**/Here i want to access the value of the method ReadData i.e displaystring and i want to store this value in the insert query below.** { get { return lmcode; } set { lmcode = value; } } string mname; public string M_Name { get { return mname; } set { mname = value; } } string desc; public string Desc { get { return desc; } set { desc = value; } } public string ReadData() { OleDbDataReader dr; string jid = string.Empty; string displayString = string.Empty; String query = "select max(LM_code)from Master_Accounts"; Datamanager.RunExecuteReader(Constr, query); if (dr.Read()) { jid = dr[0].ToString(); if (string.IsNullOrEmpty(jid)) { jid = "AM0000"; } int len = jid.Length; string split = jid.Substring(2, len - 2); int num = Convert.ToInt32(split); num++; displayString = jid.Substring(0, 2) + num.ToString("0000"); dr.Close(); } **return displayString;** I want to pass this value to the above property procedure above i.e LM_code. } public void add() { String query ="insert into Master_Accounts values ('" + LM_code + "','" + M_Name + "'," + "'" + Desc + "')"; Datamanager.RunExecuteNonQuery(Constr , query);// } If possible can u edit this code! Anticipated thanks by sameer

    Read the article

  • Is this OleDbDataAdapter bug

    - by ????
    It doesn't look to me OleDbDataAdapter should throw an exception on trying to fill DataSet for a db table column of type decimal(28,3). The message is "The numerical value is too large to fit into a 96 bit decimal". Could you just check this, I have no significant experience with ADO.NET and OLE DB components? The VB.NET code we have in the application is this: Dim dbDataSet As New DataSet Dim dbDataAdapter As OleDbDataAdapter Dim dbCommand As OleDbCommand Dim conn As OleDbConnection Dim connectionString As String 'parts where connectionString is set conn = New OleDbConnection(connectionString) 'part where sqlQuery is set but it ends up being "SELECT Price As 'Price' From PricebookView" - Price is of type decimal(28,3) dbCommand = New OleDbCommand(sqlQuery, conn) dbCommand.CommandTimeout = cmdTimeout dbDataAdapter = New OleDbDataAdapter(dbCommand) dbDataAdapter.Fill(dbDataSet) The last line is where the exception is thrown and the top of the stack trace is: at System.Data.ProviderBase.DbBuffer.ReadNumeric(Int32 offset) at System.Data.OleDb.ColumnBinding.Value_NUMERIC() at System.Data.OleDb.ColumnBinding.Value() at System.Data.OleDb.OleDbDataReader.GetValues(Object[] values) at System.Data.ProviderBase.DataReaderContainer.CommonLanguageSubsetDataReader.GetValues(Object[] values) at System.Data.ProviderBase.SchemaMapping.LoadDataRow() at System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping) at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue) at System.Data.Common.DataAdapter.Fill(DataSet dataSet, String srcTable, IDataReader dataReader, Int32 startRecord, Int32 maxRecords) at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) ... I am not sure why does it try to set the value to Int32. Thank you for the time !

    Read the article

  • Good practice to create extension methods that apply to System.Object?

    - by Christian
    Hello, I'm wondering whether I should create extension methods that apply on the object level or whether they should be located at a lower point in the class hierarchy. What I mean is something along the lines of: public static string SafeToString(this Object o) { if (o == null || o is System.DBNull) return ""; else { if (o is string) return (string)o; else return ""; } } public static int SafeToInt(this Object o) { if (o == null || o is System.DBNull) return 0; else { if (o.IsNumeric()) return Convert.ToInt32(o); else return 0; } } //same for double.. etc I wrote those methods since I have to deal a lot with database data (From the OleDbDataReader) that can be null (shouldn't, though) since the underlying database is unfortunately very liberal with columns that may be null. And to make my life a little easier, I came up with those extension methods. What I'd like to know is whether this is good style, acceptable style or bad style. I kinda have my worries about it since it kinda "pollutes" the Object-class. Thank you in advance & Best Regards :) Christian P.S. I didn't tag it as "subjective" intentionally.

    Read the article

  • insert data to table based on another table C#

    - by user1017315
    I wrote a code which takes some values from one table and inserts the other table in these values.(not just these values, but also these values(this values=values from the based on table)) and I get this error: System.Data.OleDb.OleDbException (0x80040E10): value wan't given for one or more of the required parameters.` here's the code. I don't know what i've missed. string selectedItem = comboBox1.SelectedItem.ToString(); Codons cdn = new Codons(selectedItem); string codon1; int index; if (this.i != this.counter) { //take from the DataBase the matching codonsCodon1 to codonsFullName codon1 = cdn.GetCodon1(); //take the serialnumber of the last protein string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=C:\\Projects_2012\\Project_Noam\\Access\\myProject.accdb"; OleDbConnection conn = new OleDbConnection(connectionString); conn.Open(); string last= "SELECT proInfoSerialNum FROM tblProInfo WHERE proInfoScienceName = "+this.name ; OleDbCommand getSerial = new OleDbCommand(last, conn); OleDbDataReader dr = getSerial.ExecuteReader(); dr.Read(); index = dr.GetInt32(0); //add the amino acid to tblOrderAA using (OleDbConnection connection = new OleDbConnection(connectionString)) { string insertCommand = "INSERT INTO tblOrderAA(orderAASerialPro, orderAACodon1) " + " values (?, ?)"; using (OleDbCommand command = new OleDbCommand(insertCommand, connection)) { connection.Open(); command.Parameters.AddWithValue("orderAASerialPro", index); command.Parameters.AddWithValue("orderAACodon1", codon1); command.ExecuteNonQuery(); } } } EDIT:I put a messagebox after that line: index = dr.GetInt32(0); to see where is the problem, and i get the error before that.i don't see the messagebox

    Read the article

  • Accessing MS Access database from C#

    - by Abilash
    I want to use MS Access as database for my C# windows form application.I have used OleDb driver for connecting MS Access. I am able to select the records from the MS Access using OleDbConnection and ExecuteReader.But I am un able to insert,update and delete records. My code is as follows: OleDbConnection con=new OleDbConnection(strCon); try { con.Open(); OleDbCommand com = new OleDbCommand("INSERT INTO DPMaster(DPID,DPName,ClientID,ClientName) VALUES('53','we','41','aw')", con); int a=com.ExecuteNonQuery(); //OleDbCommand com = new OleDbCommand("SELECT * FROM DPMaster", con); //OleDbDataReader dr = com.ExecuteReader(); //while (dr.Read()) //{ // MessageBox.Show(dr[2].ToString()); //} MessageBox.Show(a.ToString()); } catch { MessageBox.Show("cannot"); } If I execute the commented block the application works.But the insert block doesnt works.Why I am unable to insert/update/delete the records into database? My Connection String is as follows: string strCon="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=xyz.mdb;Persist Security Info=True";

    Read the article

  • ExecuteNonQuery: Connection property has not been initialized

    - by 20151012
    I get an error in my code: The error point at dbcom.ExecuteNonQuery();. Code(connection) public admin_addemp() { InitializeComponent(); con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\EMPS.accdb;Persist Security Info=True"); con.Open(); ds.Tables.Add(dt); ds.Tables.Add(dt2); } Code (Save button) private void save_btn_Click(object sender, EventArgs e) { OleDbCommand check = new OleDbCommand(); check.Connection = con; check.CommandText = "SELECT COUNT(*) FROM employeeDB WHERE ([EmployeeName]=?)"; check.Parameters.AddWithValue("@EmployeeName", tb_name.Text); if (Convert.ToInt32(check.ExecuteScalar()) == 0) { dbcom2 = new OleDbCommand("SELECT EmployeeID FROM employeeDB WHERE EmployeeID='" + tb_id.Text + "'", con); OleDbParameter param = new OleDbParameter(); param.ParameterName = tb_id.Text; dbcom.Parameters.Add(param); OleDbDataReader read = dbcom2.ExecuteReader(); if (read.HasRows) { MessageBox.Show("The Employee ID '" + tb_id.Text + "' already exist. Please choose another Employee ID."); read.Dispose(); read.Close(); } else { string q = "INSERT INTO employeeDB (EmployeeID, EmployeeName, IC, Address, State, " + " Postcode, DateHired, Phone, ManagerName) VALUES ('" + tb_id.Text + "', " + " '" + tb_name.Text + "', '" + tb_ic.Text + "', '" + tb_add1.Text + "', '" + cb_state.Text + "', " + " '" + tb_postcode.Text + "', '" + dateTimePicker1.Value + "', '" + tb_hp.Text + "', '" + cb_manager.Text + "')"; dbcom = new OleDbCommand(q, con); dbcom.ExecuteNonQuery(); MessageBox.Show("New Employee '" + tb_name.Text + "'- Successfuly Added."); } } else { MessageBox.Show("Employee name '" + tb_name.Text + "' already added into the database"); } ds.Dispose(); } I'm using Microsoft Access 2010 as my database and this is stand alone system. Please help me.

    Read the article

  • Trying to Insert Text to Access Database with ExecuteNonQueryin VB

    - by user3673701
    I'm working on this feature were i save text from a textbox on my form to a access database file. With the click on my "store" button I want to save the text in the corresponding textbox fields to the fields in my access database for searching and retrieving purposes. Im doing this in VB The problem I run into is the INSERT TO error with my "store" button Any help or insight as to why im getting error would be greatly appreciated. here is my code: Dim con As System.Data.OleDb.OleDbConnection Dim cmd As System.Data.OleDb.OleDbCommand Dim dr As System.Data.OleDb.OleDbDataReader Dim sqlStr As String Private Sub btnStore_Click(sender As Object, e As EventArgs) Handles btnStore.Click con = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Eric\Documents\SPC1.2.accdb") con.Open() MsgBox("Initialized") sqlStr = "INSERT INTO Master FADV Calll info (First Name, Last Name, Phone Number, Email, User Id) values (" & txtFirstName.Text & " ' ,'" & txtLastName.Text & "','" & txtPhone.Text & "', '" & txtEmail.Text & "', '" & txtUserID.Text & "', '" & txtOtherOptionTxt.Text & "','" & txtCallDetail.Text & "');" cmd = New OleDb.OleDbCommand(sqlStr, con) cmd.ExecuteNonQuery() <------- **IM RECIVING THE ERROR HERE** MsgBox("Stored") ''pass ther parameter as sq; query, con " connection Obj)" con.Close()'

    Read the article

1 2  | Next Page >