Error :Cannot Find Table 0 - c#

I am seeing an error regarding cannot find table 0, where the dataset doesn't contain the table data. This is my code to fetch rows from a table:
DataTable dt = new DataTable();
SqlConnection sqlconnection;
sqlconnection = new SqlConnection(#"connectionstring");
sqlconnection.Open();
string sql = "Select (supplier_id,name) from supplier_info where supplier_id= '"+supplierid+"'";
SqlCommand cmd = new SqlCommand(sql, sqlconnection);
cmd.CommandType = CommandType.Text;
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet dtset = new DataSet();
adpt.Fill(dt);
dt = dtset.Tables[0];
DataRow dr;
dr = dt.Rows[0];
sqlconnection.Close();
return dr;
Business logic code:
Cust_datalogic dc = new Cust_datalogic(); //datalogic class
DataTable dt = new DataTable();
DataRow dr;
dr=dc.GetSupplierInfo(id); //method
Supplier_BLL bc = new Supplier_BLL(); //business logic class
bc.Ssup_ID = dr[0].ToString();
bc.Ssup_name = dr[1].ToString();
return bc;

Your problem area in your code is
adpt.Fill(dt); //You are filling dataTable
dt = dtset.Tables[0]; // You are assigning Table[0] which is null or empty
Change it to
adpt.Fill(dtset); //Fill Dataset
dt = dtset.Tables[0]; //Then assign table to dt
OR
Your can directly use SqlDataAdapter to Fill DataTable thus no need of DataSet.
Just remove DataSet, use
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(dt);
DataRow dr = dt.Rows[0];

I had this issue when calling to web service method. Issue was with the filter / Query condition. What I was looking for it was not exist in the database. So, check if the required data exists in database.

Another way is to add a select statement after the insert query.

Related

How display table from combobox

Hi i have combobox with Table names. I would like to display selected table on button click. How to do it? This is code of my combobox
Con.Open();
SqlCommand cmd = new SqlCommand("SELECT name FROM sys.tables", Con);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("name", typeof(string));
dt.Load(rdr);
wczytywanie.ValueMember = "name";
wczytywanie.DataSource = dt;
Con.Close();
now i would like to display these tables in dataGridView after button click.This is not working.
Con.Open();
SqlCommand cmd = new SqlCommand("SELECT * from sys.tables where name=#name", Con);
cmd.Parameters.Add("name", wczytywanie.SelectedValue.ToString());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
Dane.DataSource = dt;
Con.Close();
try adding DisplayMember and assign value "name"
wczytywanie.ValueMember = "name";
wczytywanie.DisplayMember = "name";
This might do
conn = new MySqlConnection(connectString);
conn.Open();
comm = new MySqlCommand(query, conn);
MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn);
DataSet DS = new DataSet();
adapter.Fill(DS);
advancedDataGridView1.DataSource = DS.Tables[0];
conn.Close();
And to change the column name your sql be like columnname as 'your preferred column name'
SELECT principal_id as 'Principal ID' from sys.tables where name=#name"

Passing Datagridview to dataset

Hello internet so first i am newbie at c# and i am doing project about changing data from a sql table. I passed the result of the query to the datatable and datagridview, but what i want next is i want the modified datagridview table passing to a dataset. this is how i get my table from the sql:
string query = "select Article,Barcode,\"Minimum Stock\",\"Current Stock\" from article where Fid=2 and \"Minimum Stock\" > \"Current Stock\"";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
da.Dispose();
Now the users will modifie the table and valid the information. How can i save it to a dataset?
I tried to bind dataset to the datagridview:
Dataset1.Tables.Add(datagridview1.datasource);
But it threw a error where it says datasource doesn't use here
Can anyone help?

Unable to get GRIDVIEW when new column added

This is my SEARCH Function with gridview.I'm not able to get gridview in Form remaining all are fine.Here i added new columns two.Please help me out.thanks
private void txtSearch02()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("select ItemCode,ItemName,PointsNeeded from tb_ItemRedemption where (ItemCode is null or ItemCode='" + txtkey2.Text.Trim() + "') or (ItemName is null or ItemName='" + txtkey2.Text.Trim() + "')", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
Session["ItemCode"] = dt;
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
dt = ds.Tables[0];
con.Close();
dt.Columns.Add("Quantity");
dt.Columns.Add("TotalPoints");
// for caliculation
txtPointsNeeded.Text = dt.Rows[0]["PointsNeeded"].ToString();
//dt.Rows[0]["Quantity"].ToString();
//dt.Rows[0]["TotalPoints"].ToString();
DataRow dr;
dr = dt.NewRow();
dt.Rows.Add(dr);
// for caliculation
txtGetQuantity.Text = txtQuantity.Text;
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
}
Following on from my comments regarding parameterising the query and using the 'using(){}' statement I'd start by writing something like this:
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(myStr))
{
string sql = "select ItemCode,ItemName,PointsNeeded from tb_ItemRedemption where (ItemCode is null or ItemCode = #txtkey2) or (ItemName is null or ItemName = #txtkey2)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#txtkey2", txtkey2.Text.Trim());
SqlDataAdapter sda = new SqlDataAdapter(cmd);
//You're currently adding a blank DataTable to a session variable below as you've not
//filled it yet. I've left this incase that's what you meant to do.
Session["ItemCode"] = dt;
con.Open();
//SqlDataAdapter should be able to fill a DataTable as well as a dataset.
sda.Fill(dt);
if (dt.Rows.Count > 0) //Put a breakpoint here to check if anything is returned in dt
{
dt.Columns.Add("Quantity");
dt.Columns.Add("TotalPoints");
// for caliculation
txtPointsNeeded.Text = dt.Rows[0]["PointsNeeded"].ToString();
//Not sure what you're trying to do here. You're just adding a blank row to dt.
DataRow dr;
dr = dt.NewRow();
dt.Rows.Add(dr);
// for caliculation
txtGetQuantity.Text = txtQuantity.Text;
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
}
else
{
//Code to handle nothing being returned.
}
}
If you have previous three columns (with bindvalue) and add other two columns, It would be confusing one for it.
Add all the columns to datatable again. means three and new two.
Try it. It should work.cause your code is right.
Make Sure your Auto Generated Columns is set to 'true'.
Go to properties of grid view, and change auto generated columns to true in case of false.
Go through the links for further clarification : Click here

Unable to cast object of type 'System.Data.DataColumn' to type 'System.IConvertible'

I tried to save a record from a query into a DataRow, but did not make it. I could need some help. This my code:
private DataSet CreateDataSet()
{
DataSet ds = new DataSet();
// create Countries table and columns
DataTable dtApplications = ds.Tables.Add("Applications");
DataColumn dtApplicationID = dtApplications.Columns.Add("ApplicationID", typeof(int));
DataColumn dtApplicationName= dtApplications.Columns.Add("ApplicationName", typeof(string));
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(MoahannedConnectionString);
SqlCommand cmd1 = new SqlCommand("select AppID,AppName from Application", con);
SqlDataAdapter da = new SqlDataAdapter();
SqlDataReader sdr = null;
dt.TableName = "Application";
con.Open();
sdr = cmd1.ExecuteReader();
while (sdr.Read())
{
AddDataToTable(dtApplicationID, dtApplicationName, dtApplications, ds);
}
}
private void AddDataToTable(DataColumn ID, DataColumn Name, DataTable myTable,DataSet ds)
{
DataRow row;
row = myTable.NewRow();
row["ApplicationID"] = ID;
row["ApplicationName"] = Name;
myTable.Rows.Add(row);
}
You can use the DataAdapter directly to load a DataTable:
using(var da = new SqlDataAdapter("select AppID,AppName from Application", con))
{
da.Fill(dt);
}
The rest of the code above is redundant in my opinion.
Side-note: You're getting the exception because you want to pass a field of a record to a DataRow's field. But actually you're passing the DataColumn.
This would work but is unnecessary:
row["ApplicationID"] = sdr.GetInt32(sdr.GetOrdinal("ApplicationID"));
row["ApplicationName"] = sdr.GetString(sdr.GetOrdinal("ApplicationName"));
Where sdr is your DataReader.

How to insert a row using a IDbDataAdapter(SqlDataAdapter or OleDbDataAdapter) without loading the entire table?

I need to insert a row into a DataTable using a OleDbDataAdapter. However, my table has more than 100000 records and I don't want to load all the records.
My current code loads all the records into the DataTable
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Nodes", _cnAq9);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr = dt.NewRow();
dr["nID"] = nNodeID;
dr["csNumber"] = strNumber;
dt.Rows.Add(dr);
da.Update(dt);
Is there a way to insert data into my table without filling my datatable with all the rows other than adding "where 1 = 0" to my statement
EDIT
I need to use a DataAdapter to do this
Call FillSchema instead of Fill
As per request:
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Nodes", _cnAq9);
DataTable dt = new DataTable();
da.FillSchema(dt, SchemaType.Source);
DataRow dr = dt.NewRow();
dr["nID"] = nNodeID;
dr["csNumber"] = strNumber;
dt.Rows.Add(dr);
da.Update(dt);
Yes, by using the DbCommand class to execute an INSERT.
Your code will probably look something like
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
var query = "INSERT INTO Nodes (nID, csNumber) " +
"VALUES (?, ?)";
var command = new OleDbCommand( query, connection);
command.Parameters.AddWithValue("#nID", nNodeID);
command.Parameters.AddWithValue("#csNumber", strNumber);
connection.Open();
command.ExecuteNonQuery();
}
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Nodes", _cnAq9);
DataTable dt = new DataTable();
da.FillSchema(dt, SchemaType.Source);
DataRow dr = dt.NewRow();
dr["nID"] = nNodeID;
dr["csNumber"] = strNumber;
dt.Rows.Add(dr);
da.Update(dt);
try
oleconnStkNames = new OleDbConnection(strAccessConnectionString);
oleconnStkNames.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = oleconnStkNames; //new OleDbConnection(strAccessConnectionString);
cmd.CommandText = "TheName of your InsertQuery "; // name of the query you want to run
cmd.CommandType = CommandType.StoredProcedure; // or System.Data.CommandType.Text if you are not using a Access StoredProc
OleDbDataReader rdr = cmd.ExecuteReader();
catch (Exception ex)
{
bla..bla..bla
}
//if you want to wrap it in a using() and add transactional processing use this example that I've written to fit what ever it is you are doing..
using (OleDbCommand olecmdStkNames = new OleDbCommand(strSQL, oleconnStkNames))
{
olecmdStkNames.CommandTimeout = 60;
oletransStockList = oleconnStkNames.BeginTransaction();
olecmdStkNames.Transaction = oletransStockList;
olecmdStkNames.CommandType = System.Data.CommandType.Text;
try
{
intRecordsAffected = olecmdStkNames.ExecuteNonQuery();
oletransStockList.Commit();
}
catch (OleDbException oledbExInsert_Update)
{
oletransStockList.Rollback();
Console.WriteLine(oledbExInsert_Update.Message);
}
((IDisposable)oletransStockList).Dispose();
}

Categories

Resources