SQL query runs, but not producing any results - c#

I have a following query to display Student data in dataGridView, but it doest seems to display any records at all. My code:
public void setSQL()
{
string ConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\jasper\\Desktop\\AutoReg\\AutoReg.accdb;";
OleDbConnection MyConn = new OleDbConnection(ConnStr);
MyConn.Open();
DataSet ds = new DataSet();
//query to ask
string query = "SELECT * FROM Student";
using (OleDbCommand command = new OleDbCommand(query, MyConn))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds;
MyConn.Close();
}
}
}

edit: After seeing the comment I noticed my error. I was assuming a web application.
You should use a DataTable as a data source, not a DataSet. Set the data source property to the first table in the DataSet's tables collection.
In truth, you can use a DataSet, but it's not so straightforward. It does allow the user to change the table she's seeing, though.

Couple of things you can check.
Are you sure you have entries in this table?
Try commenting out the part about the OleDbDataAdapter, use a DataReader instead so you can step through and see if there are rows being returned.
if you are getting rows in your datareader, then it may have to do with your datagrid set up. Are you using autogenerate columns? If not, are the columns set up correctly?

Instead of:
dataGridView1.DataSource = ds;
Try this:
dataGridView1.DataSource = ds.Tables[0];

Related

`DataTable` does not contain a definition for 'Fill' - c#

I am not understanding why I am getting an error after reading documentation in regards to the .Fill(). Am I missing something that is causing this to return with an error?
protected void FillData()
{
using (SqlConnection connection = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB;AttachDbFilename= C:\Users\home\Documents\C# Programs\shop\Database.mdf ;Integrated Security = True"))
{
connection.Open();
using (SqlDataAdapter dataAdapter = new SqlDataAdapter("select * from Employee", connection))
{
DataTable table = new DataTable();
table.Fill(table);
employeeDataGridView.DataSource = table;
}
}
}
The problem is in this line of code
table.Fill(table);
You can't use table, to fill your table. The correct syntax would be
dataAdapter.Fill(table)
You can't populate a DataTable in that way, you need to fill your DataAdapter, use a DataSet and then set the DataGridView to use this.
using (SqlDataAdapter dataAdapter = new SqlDataAdapter("select * from Employee", connection))
{
var ds = new DataSet();
dataAdapter.Fill(ds);
employeeDataGridView.DataSource = ds.Tables[0];
}
The neatest way to code this up is:
protected void FillData()
{
using (SqlDataAdapter dataAdapter = new SqlDataAdapter("select * from Employee", #"Data Source = (LocalDB)\MSSQLLocalDB;AttachDbFilename= C:\Users\home\Documents\C# Programs\shop\Database.mdf ;Integrated Security=True"))
{
DataTable table = new DataTable();
dataAdapter.Fill(table);
employeeDataGridView.DataSource = table;
}
}
It'll get neater if you put your connection string in a static "global" variable somewhere
Points of note:
use the dataadapter constructor that takes two strings - it will create the connection and the command for you
you don't need to open the connection for the adapter- it knows how to
this means you can have just one using
if your sql needs parameters put them inside the using as dataAdapter.SelectCommand.Paramaters.Add...
you could turn this into a method that accepts any sql string and parameter collection and returns you a datatable
consider putting a WHERE clause in your sql; users might not like to see a grid with 20,000 employees in because it makes it harder to edit a handful of employees
It would be better to add a DataSet to your project (right click project, add>>new item, choose dataset - it gives you something that looks like a db visual design surface you can add queries to, create datatables that become components that can be added to your forms/create databound controls automatically) and create strongly typed datatables and table adapters
An alternative better route than this would be to use Dapper and strongly typed POCOs

OleDbDataAdapter error after change in database

I haven been trying to figure this out all day and just couldn't find my mistake. I have an ms-access database and a c# program that is supposed to update the data in the db. Unfortunately I keep getting System.Data.OleDb.OleDbException: Syntaxerror in update statement.
I am using OleDbConnectionand OleDbDataAdapter and everything (except for one column) was working perfectly. I couldn't figure out why I kept getting the above mentioned error for that column (it was formatted just like the others -> text), so I deleted the column and created it again. Now I get the error for every single alteration I try to make.
public void changeFields(string id, string name, string famName, string department) {
DataSet myDS = new DataSet();
using (OleDbConnection conn = new OleDbConnection(connectionString)) {
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand("SELECT * FROM Table WHERE ID = '"+ id +"', conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
myDS.Tables["Table"].Rows[0]["Name"] = name;
myDS.Tables["Table"].Rows[0]["FamilyName"] = famName;
myDS.Tables["Table"].Rows[0]["Department"] = department;
adapter.Update(myDS, "Table");
conn.Close();
}
}
The names of the columns are correct and if I
Console.WriteLine(myDS.Tables["Table"].Rows[0]["Name"];
right before I try to update.
I actually get the correctly changed version. The error always occurs for line adapter.Update();
Is it possible that access rearranges or messes some index up when I insert a column into the database?
Help would be very much appreciated
I figured it out! The problem was that I had a reserved keyword as a column name. Now it all works perfectly fine

Combobox added to datagridview losses its selection

I am trying to populate a datagrid table and add an additional combobox in a Winforms application to allow the user to select from an exception list.
The datagrid is populated using a Stored Procedure on SQL server.
(NOTE: due to my ITs security I have to go through a single server using linked servers to where the data is to query the data so the stored procedure uses dynamic SQL)
The data pulls properly and the additional combobox appears however once I select an exception on 1 row and try to go to the next row, the first combobox's selection disappears.
An additional question, given the nature or how I query the data, how would I update the data on the original sql tables from datagrid? Another stored procedure?
FYI, I'm a SQL developer but I'm fairly new to C#
My code is below for the datagridview method. Thanks in advance.
public void displayDataGridView(string param)
{
SqlConnection con = new SqlConnection("Data Source = SQLServer1; initial catalog=GlbDBNames; integrated security=true ");
{
SqlCommand cmd;
cmd = new SqlCommand(param, con);
cmd.CommandTimeout = 60 * 20;
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dg_batchsummary.DataSource = ds.Tables[0];
dg_batchsummary.Columns[0].Width = 200;
dg_batchsummary.AutoGenerateColumns = false;
dg_batchsummary.AllowUserToAddRows = false;
DataGridViewComboBoxColumn ExceptionList = new DataGridViewComboBoxColumn();
ExcptionList.HeaderText = "Exception List";
ExceptionList.Name = "Newexcept";
ExceptionList.Items.AddRange("Item1","Item2","Item3");
dg_batchsummary.Columns.Add(ExceptionList);
}

object reference not set to an instance of an object when using parameter

Can someone tell me how i can set the object reference to an instance? ....
Here, user_id is the parameter which takes a textbox value into the sql statement.
private void button1_Click(object sender, EventArgs e)
{
OracleConnection con = new OracleConnection("Data Source=KBETEST; Persist Security Info=TRUE; User ID=dbo; Password=dbo123; Unicode=True");
DataSet ds = new DataSet();
OracleDataAdapter adap = new OracleDataAdapter();
OracleCommandBuilder b = new OracleCommandBuilder(adap);
adap = new OracleDataAdapter("insert into banks_ben_branch_99 (ben_bank_id, ben_brn_code, brn_name,ben_brn_addr1, ben_brn_loc, ben_brn_state, ben_brn_city, ben_bank_city, coun_code,brn_stat, remarks, brn_id, user_id, pc_tcp_ip, rtgs_stat, pay_brn_code,sys_date) select bankid,benbrn_code,brn_name,substr(brn_addr,1,100),brn_loc, brn_stat, brn_city, brn_city, coun_code,'A', remarks, '15', :user_id,'172.20.1.109', rtgs_stat, benbrn_code,sysdate from bbbt",con);
adap.InsertCommand.Parameters.Add("user_id", OracleType.VarChar,20, "user_id").Value = textBox1.Text;
adap.Fill(ds,"A");
DataTable table = ds.Tables["A"];
dataGridView1.DataSource = ds.Tables["A"];
con.Dispose();
}
thanks!
edit
private void button1_Click(object sender, EventArgs e)
{
OracleConnection con = new OracleConnection("Data Source=KBETEST; Persist Security Info=TRUE; User ID=dbo; Password=dbo123; Unicode=True");
DataSet ds = new DataSet();
OracleDataAdapter adap = new OracleDataAdapter();
OracleCommandBuilder b = new OracleCommandBuilder(adap);
string str = "insert into banks_ben_branch_99 (ben_bank_id, ben_brn_code, brn_name,ben_brn_addr1, ben_brn_loc, ben_brn_state, ben_brn_city, ben_bank_city, coun_code,brn_stat, remarks, brn_id, user_id, pc_tcp_ip, rtgs_stat, pay_brn_code,sys_date) select bankid,benbrn_code,brn_name,substr(brn_addr,1,100),brn_loc, brn_stat, brn_city, brn_city, coun_code,'A', remarks, '15', :user_id, '172.20.1.109', rtgs_stat, benbrn_code,sysdate from bbbt";
con.Open();
adap.InsertCommand = new OracleCommand(str, con);
adap.InsertCommand.Parameters.Add("user_id", OracleType.VarChar,20).Value = textBox1.Text;
adap.InsertCommand.ExecuteNonQuery();
con.Dispose();
}
thanks everyone for your help!! i got it!
EDIT: There are multiple things wrong with your code:
You're not specifying the user_id parameter in the command, although it's in the SQL
You're trying to use the InsertCommand of the adapter even though you haven't specified any insertion SQL
You're trying to fill a dataset, but you haven't specified a query - just an insert command.
I suspect you shouldn't be using a data adapter at all. If you just need to insert some data, use:
using (var connection = new OracleConnection(...)
{
connection.Open();
string sql = "insert into banks_ben_branch_99 [... as before ...]";
using (var command = new OracleCommand(sql, conn))
{
command.Parameters.Add("user_id", OracleType.VarChar, 20)
.Value = textBox1.Text;
command.ExecuteNonQuery();
}
}
I suspect adap.InsertCommand is null in the following line:
adap.InsertCommand.Parameters.Add
On the previous line you use the following constructor:
adap = new OracleDataAdapter("insert into ...", con);
but this constructor initializes the SelectCommand, not the InsertCommand. Therefore adap.InsertCommand will still have its default value, null.
Your code then goes on to attempt to fill a DataTable using this adapter:
adap.Fill(ds,"A");
but this won't work either: you need a SelectCommand to do this.
To fill a DataSet, your code should probably look something like:
adap = new OracleDataAdapter("SELECT ... FROM ... WHERE ...", con);
adap.SelectCommand.Parameters.Add(... any parameters you need ...);
adap.Fill(ds, "A");
it is passing the break point now, no changes has been made to the oracle database tables! why is this happening.
I think you're misunderstanding how DataAdapters work.
To get data from the database into your DataTable, you need to:
Create an adapter with a SelectCommand
Call adapter.Fill to execute the SelectCommand and fill the DataTable with the result
To insert data into the database from your DataTable, you need to:
Insert a row into your DataTable with the data you want to insert
Create an adapter with an InsertCommand
Call adapter.Update to insert the data into the database.
Updating / Deleting rows in the database is similar to inserting, but uses UpdateCommand and DeleteCommand.
I think user_id is not a nullable column and it occurs when your parameter is empty. First thing is, parameter name does not match. After that, it still can happen when textbox is empty. It is better to check on client side for validation.
The parameter that you have given is null.

c# Textbox filling with dataset from MYsql?

I am trying to populate some text boxes on a form with data pulled from MySQL into a data set.
I cant seem to get the code right and could use some help
string ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection;
MySqlDataAdapter adapter;
DataTable DTItems;
connection = new MySqlConnection(ConnectionString);
try
{
//prepare query to get all records from items table
string query = "select * from spt_proposal where fr_Numer = "+ a+"";
//prepare adapter to run query
adapter = new MySqlDataAdapter(query, connection);
DataSet DS = new DataSet();
//get query results in dataset
adapter.Fill(DS);
textBox5.Text = DS.Tables[0].Rows[0].ToString();
This does not hit the text box at all.
a in the query is a variable that is pulled from a different form
and the query should pull 32 different things from the database in a row
There are about 9 text boxes on the form that i will have to fill with different data from this row.
Anyone have a better way to do this?
Brent
Try:
textBox5.Text = DS.Tables[0].Rows[0][0].ToString();
Remember, that a Table is pretty much a two dimensional array. Your code literally gets to the 1st row in the DataSet, but doesn't take into account the Column.

Categories

Resources