How to resolve Invalid Object Name "Table Name" in C#? - c#

When I am running My application in Visual Studio 2008 it is showing me Message Box with notation of Invalid Object Name "Table name", instead the table is already there in my database. So please help me to solve this problem.
private void FrmInwardDisp2_Load(object sender, EventArgs e)
{
byte _true = 1;
byte _false = 0;
//this.toolTip1.SetToolTip(this.dgvDisplay, "Double Click to Edit");
int width = Screen.PrimaryScreen.Bounds.Width;
int height = Screen.PrimaryScreen.Bounds.Height - 175;
dgvDisplay.Width = width - 25;
dgvDisplay.Height = height;
//dgvDisplay.AutoSize = true;
try
{
SqlConnection con = new SqlConnection(Variables.con);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.SelectCommand = cmd;
switch (Static_Class.selected)
{
case 1:
{
btnAddInward.Text = "Add Rental Inward";
cmd.CommandText = "SELECT [RentalInwardNo],[VoucherNo],[NameOfWork]
[Location],[NameOfVendor],[VendorCode],[VendorItemCode],[ItemName],
[Narration],[WareHouse],[DriverName],[VehicleNo],[RejectedItemCode],
[RejectedItemName],[Rate],[Date],[InvoiceNo],[ChallanNo],[TenderCode],
[PINo],[PONo],[UnitQty],[UOM],[RequisitionNo],[ReceivedBy],
[LocationID],[Layer],[Local],[Global],[DeleteStatus],[AutoGenerated]
FROM IN_Rental_Inward
where [TenderCode]= " + Static_Class.tendercode + "
and [LocationID]='" + Static_Class.LocationID + "'
and [Layer]='" + Static_Class.Layer + "'
and [DeleteStatus]=" + 0;
try
{
//con.Open();
da.Fill(ds, "TableDisplay");
da.Dispose();
cmd.Dispose();
//con.Close();
dgvDisplay.DataSource = ds.Tables["TableDisplay"];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
break;

In your query text, specify the table's schema name also before the table name. For example:
cmd.CommandText = "SELECT … FROM dbo.IN_Rental_Inward …";
// ^^^^

Related

create at run time multiple text box and assign value textbox from database..i want to show all the data from database

How can i create at run time multiple text box and assign value to textbox from database..i want to show all the data from database. For example if i have store 4 rows then program should show all 4 rows in dynamically created text boxes at once. C# window form give me code or example thanks..
int txtno = int.Parse(textBox1.Text);
try
{
string MyConnection2 = "datasource = 127.0.0.1;port=3306;username = root;password =; database = test123; SslMode=None ;Convert Zero Datetime=True";
//Display query
string Query = "select * from test123.task;";
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
// MyConn2.Open();
//For offline connection we weill use MySqlDataAdapter class.
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataSet ds = new DataSet();
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
MyAdapter.Fill(ds);
// MySqlDataReader MyReader2;
foreach (DataRow de in DataSet.TABLe.Row)
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
if (MyReader2.Read())
{
string val = MyReader2[0].ToString();
if (val == "")
{
//textBox1.Text = ()
}
else
{
txtno = Convert.ToInt32(MyReader2[0].ToString());
txtno = txtno + 1;
TextBox txt = new TextBox();
// txtno.Text = (i + 1).ToString()
panel2.Controls.Add(txt);
panel2.Show();
textBox1.Text = txtno.ToString();
}
}
//for (int i = 0; i < txtno; i++)
//{
// Label lbl = new Label();
// lbl.Text = (MyReader2["task_comment"].ToString());
// // lbl = "Label" + i.ToString();
// panel2.Controls.Add(lbl);
//}
MyConn2.Close();//Connection closed here
}
catch (Exception ex)
{
}
There are lots of better ways of programing what you want but I provide a simple way to fix your code by specifying the Top and Left of your Textboxes :
MySqlConnection con = new SqlConnection( "datasource = 127.0.0.1;port=3306;username = root;password =; database = test123; SslMode=None ;Convert Zero Datetime=True");
MySqlCommand cmd = new SqlCommand( "select * from test123.task;", con);
con.open();
MySqlDataReader dr= cmd.ExecuteReader();
int top=100;
While(dr.read())
{
Textbox textBox= new TextBox();
panel2.Controls.Add(textBox);
textBox.Text=dr[0 /* or instead of 0 use your fieldName */].ToString();
textBox.Left=150;
textBox.Top=top;
top+=100;
}
con.close()

Object can't be "InvalidCastException: The OleDbParameter" in catch

I an trying to do a simple task of reading from one table "tab2" in a database->save to xml and then reload it into table "tab1" both have the same structure, I asked previously and received the following code as an answer.
I am having problems I am now getting the database filed ONCE per item but with a date time stamp I don't think its writing the XML from reading the database properly I am running it twice to get the schema and once for data.
private void button1_Click(object sender, EventArgs e)
{
try
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.accdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
//Conn.Close();//severl times connection has been open
Conn.Open();
DataSet ds = new DataSet();
ds.ReadXml(#"c:\\temp\\tab2.xml");
OleDbCommand cmd = new OleDbCommand();
//OleDbCommand cmd1 = new OleDbCommand();
DataTable dtCSV = new DataTable();
dtCSV = ds.Tables[0];
cmd.Connection = Conn;
cmd.CommandType = CommandType.Text;
//cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[0][0])));// = 1234;
//cmd1.Connection = Conn;
for (int row = 0; row <= dtCSV.Rows.Count - 1; row++)
{
//for (int col = 0; col < dtCSV.Columns.Count - 1; col++)
//{
// //cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (dtCSV.Rows ,dtCSV.Columns)");
//}
cmd.Parameters.Clear();
if (dtCSV.Columns.Count > 1)
{
//command.Parameters.Add(new OleDbParameter("#EMPID", Convert.Tostring(empsplitIt[1])));
//cmd.Parameters.Add(dtCSV.Rows[row][0]);
cmd.Parameters.Add(new OleDbParameter("#Field1", Convert.ToString(dtCSV.Rows[row][0])));
cmd.Parameters.Add(new OleDbParameter("#dtCSV", Convert.ToString(dtCSV.Rows[row][1])));
cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (? , ?)");
cmd.ExecuteNonQuery();
}
}
//Conn.Close();
}
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
private void button2_Click(object sender, EventArgs e)
{
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
string strSql = "Select * from Table1"; //only launch in main
richTextBox1.Text = richTextBox1.Text + " Querying Launch Parameters";
try
{
OleDbConnection con = new OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = C:\\temp\\names.mdb; Persist Security Info = False");
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "fname,sname");
// Extract data set to XML file
ds.WriteXml(#"c:\\temp\\tab2.xml", XmlWriteMode.WriteSchema);
ds.WriteXml(#"c:\\temp\\tab2.xml");
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
}
}
}
I find from my code that there is two different connection strings with in it when I putin the corect spelling correcting these it now fails on the line
dtCSV = ds.Tables[0];
with this
Error System.IndexOutOfRangeException: Cannot find table 0.
at System.Data.DataTableCollection.get_Item(Int32 index)
at WindowsFormsApp8.Form1.button1_Click(Object sender, EventArgs e) in
Code:
private void button1_Click(object sender, EventArgs e)
{
try
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
//Conn.Close();//severl times connection has been open
Conn.Open();
DataSet ds = new DataSet();
ds.ReadXml(#"c:\\temp\\tabel2.xml");
OleDbCommand cmd = new OleDbCommand();
//OleDbCommand cmd1 = new OleDbCommand();
DataTable dtCSV = new DataTable("tabel1");
dtCSV = ds.Tables[0];
cmd.Connection = Conn;
cmd.CommandType = CommandType.Text;
//cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[0][0])));// = 1234;
//cmd1.Connection = Conn;
for (int row = 0; row <= dtCSV.Rows.Count - 1; row++)
{
//for (int col = 0; col < dtCSV.Columns.Count - 1; col++)
//{
// //cmd.CommandText = ("INSERT INTO tab1 ( field1, field2) VALUES (dtCSV.Rows ,dtCSV.Columns)");
//}
cmd.Parameters.Clear();
if (dtCSV.Columns.Count > 1)
{
//command.Parameters.Add(new OleDbParameter("#EMPID", Convert.Tostring(empsplitIt[1])));
//cmd.Parameters.Add(dtCSV.Rows[row][0]);
cmd.Parameters.Add(new OleDbParameter("#field1", Convert.ToString(dtCSV.Rows[row][0])));
cmd.Parameters.Add(new OleDbParameter("#field2", Convert.ToString(dtCSV.Rows[row][1])));
cmd.CommandText = ("INSERT INTO tabel1 ( field1, field2) VALUES (? , ?)");
cmd.ExecuteNonQuery();
}
}
//Conn.Close();
}
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
private void button2_Click(object sender, EventArgs e)
{
{
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\temp\\names.mdb;Persist Security Info=False");
using (OleDbConnection Conn = new OleDbConnection(ConnString))
{
string strSql = "Select * from tabel2"; //only launch in main
richTextBox1.Text = richTextBox1.Text + " Querying Launch Parameters";
try
{
OleDbConnection con = new OleDbConnection(ConnString);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "fname,sname");
// Extract data set to XML file
ds.WriteXml(#"c:\\temp\\tabel2.xml", XmlWriteMode.WriteSchema);
ds.WriteXml(#"c:\ \temp\\tabel2.xml");
}
catch (Exception ex)
{
richTextBox1.Text = richTextBox1.Text + "\n Error " + ex + "\n"; ;
}
}
}
}
}

How do i get data from multiple access tables into a C# windows form?

I am trying to display data from four different database tables using the code below, this method works perfectly for one table but i cant get my head around making it work for multiple, here is the code:
private void Assign_Load(object sender, EventArgs e)
{
try
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ConnectionDetail.Warehouse;
string sql = "Select * from [Location], [Assign], [Products], [staff]";
da = new OleDbDataAdapter(sql, conn);
da.Fill(dt); // filling the database information into databtable
//Location Table
DataRow dr = dt.Rows[currentRow]; // counting the rows
txtLocID.Text = dr["Location ID"].ToString();
txtAisle.Text = dr["Aisle Code"].ToString();
txtSection.Text = dr["Section"].ToString();
txtShelf.Text = dr["Shelf"].ToString();
txtLocation.Text = dr["Location"].ToString();
txtLength.Text = dr["Length"].ToString();
txtWidth.Text = dr["Width"].ToString();
lstSize.Text = dr["Size Description"].ToString();
//Product Table
txtSKU.Text = dr["SKU"].ToString();
txtDes.Text = dr["Description"].ToString();
listHaz.Text = dr["Hazardous"].ToString();
listLiq.Text = dr["Liquid"].ToString();
txtQuan.Text = dr["Quantity"].ToString();
txtWeig.Text = dr["Weight"].ToString();
lstSize.Text = dr["Size Description"].ToString();
//Satff Table
txtID.Text = dr["StaffID"].ToString();
//Assign Table
txtAssID.Text = dr["Assign ID"].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
{
OleDbConnection load = new OleDbConnection();
load.ConnectionString = ConnectionDetail.Warehouse;
OleDbCommand cmds = new OleDbCommand();
lbltime.Text = DateTime.Now.ToString("yyyy MMM ddd HH:mm");
try
{
load.Open();
cmds = new OleDbCommand();
cmds.CommandText = "SELECT * FROM [Location], [Assign], [Products], [staff];";
cmds.Connection = load;
dr = cmds.ExecuteReader();
}
catch (Exception err)
{
//Any database errors jump here and output error message
MessageBox.Show("A database error has occurred: " + Environment.NewLine + err.Message);
}
finally
{
// btnNext_Click(sender, e);
txtLocID.Visible = false;
}
}
}
The best answer, is to update your SQL statement to use a JOIN statement. Assuming your data / tables are somehow related.
Else, the other way to do it, is to create separate functions to populate each set of Text items separately.
Looking at your code, I'm betting you should consider "binding".
Figured it out, this works just as well as all your suggestions, thanks for everyone's help anyway.
OleDbConnection Cons = new OleDbConnection(); // new connection
OleDbDataReader dr;
int currentRow = 0;
//Location
DataTable dt = new DataTable();
OleDbDataAdapter da;
//Product
DataTable dt1 = new DataTable();
OleDbDataAdapter da1;
//staff
DataTable dt2 = new DataTable();
OleDbDataAdapter da2;
//Assign
DataTable dt3 = new DataTable();
OleDbDataAdapter da3;
private void Assign_Load(object sender, EventArgs e)
{
try
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ConnectionDetail.Warehouse;
string sql = "Select * from Location";
da = new OleDbDataAdapter(sql, conn);
da.Fill(dt); // filling the database information into databtable
//Location Table
DataRow dr = dt.Rows[currentRow]; // counting the rows
txtLocID.Text = dr["Location ID"].ToString();
txtAisle.Text = dr["Aisle Code"].ToString();
txtSection.Text = dr["Section"].ToString();
txtShelf.Text = dr["Shelf"].ToString();
txtLocation.Text = dr["Location"].ToString();
txtLength.Text = dr["Length"].ToString();
txtWidth.Text = dr["Width"].ToString();
lstSize.Text = dr["Size Description"].ToString();
//Product Table
OleDbConnection conn1 = new OleDbConnection();
conn1.ConnectionString = ConnectionDetail.Warehouse;
string sql1 = "Select * from Products";
da1 = new OleDbDataAdapter(sql1, conn1);
da1.Fill(dt1); // filling the database information into databtable
DataRow dr1 = dt1.Rows[currentRow]; // counting the rows
txtSKU.Text = dr1["SKU"].ToString();
txtDes.Text = dr1["Description"].ToString();
listHaz.Text = dr1["Hazardous"].ToString();
listLiq.Text = dr1["Liquid"].ToString();
txtQuan.Text = dr1["Quantity"].ToString();
txtWeig.Text = dr1["Weight"].ToString();
lstSize1.Text = dr1["Size Description"].ToString();
//Staff Table
OleDbConnection conn2 = new OleDbConnection();
conn2.ConnectionString = ConnectionDetail.Warehouse;
string sql2 = "Select * from Staff";
da2 = new OleDbDataAdapter(sql2, conn2);
da2.Fill(dt2); // filling the database information into databtable
DataRow dr2 = dt2.Rows[currentRow]; // counting the rows
txtID.Text = dr2["StaffID"].ToString();
//Assign Table
OleDbConnection conn3 = new OleDbConnection();
conn3.ConnectionString = ConnectionDetail.Warehouse;
string sql3 = "Select * from Assign";
da3 = new OleDbDataAdapter(sql3, conn3);
da3.Fill(dt3); // filling the database information into databtable
DataRow dr3 = dt3.Rows[currentRow]; // counting the rows
txtAssID.Text = dr3["Assign ID"].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
{
OleDbConnection load = new OleDbConnection();
load.ConnectionString = ConnectionDetail.Warehouse;
OleDbCommand cmds = new OleDbCommand();
lbltime.Text = DateTime.Now.ToString("yyyy MMM ddd HH:mm");
try
{
load.Open();
cmds = new OleDbCommand();
cmds.CommandText = "SELECT * FROM Location;";
cmds.CommandText = "SELECT * FROM Products;";
cmds.CommandText = "SELECT * FROM Staff;";
cmds.CommandText = "SELECT * FROM Assign;";
cmds.Connection = load;
dr = cmds.ExecuteReader();
}
catch (Exception err)
{
//Any database errors jump here and output error message
MessageBox.Show("A database error has occurred: " + Environment.NewLine + err.Message);
}
finally
{
// btnNext_Click(sender, e);
txtLocID.Visible = false;
}
}
}

Input string was not in a correct format in Sales Order

I am having this problem
Input string was not in a correct format.
highlighted to the part of:
DisplayOrder(Convert.ToInt16(txtOrderNo.Text));
DisplayOrderDetails(Convert.ToInt16(txtOrderNo.Text));
I am having a hard time figuring out what is the error, can you help me? Thank you very much.
Here is my set codes:
private void displayNavigate()
{
DisplayOrder(Convert.ToInt16(txtOrderNo.Text));
DisplayOrderDetails(Convert.ToInt16(txtOrderNo.Text));
double dTotal = 0;
try
{
for (int nRow = 0; nRow <= grdDetails.Rows.Count - 1; nRow++)
{
dTotal = dTotal + Convert.ToDouble((grdDetails.Rows[nRow].Cells["Amount"].Value.ToString()));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
lblTotal.Text = string.Format("{0:#,##00.00}", dTotal);
}
//================================================================================
//================================================================================
private void DisplayOrder(int nOrderNo)
{
try
{
OpenConnection();
SqlCommand cmdSelect = new SqlCommand();
cmdSelect.Connection = cn;
cmdSelect.CommandType = CommandType.Text;
cmdSelect.Transaction = trnOrder;
cmdSelect.CommandText = "SELECT " +
"B.OrderNo, B.OrderDate, A.CustomerNo, " +
"A.CustomerName, A.CustomerAddress, B.PurchaseOrderNo, B.AgentName, B.Status " +
"FROM Customers AS A, Orders AS B " +
"WHERE A.CustomerNo = B.CustomerNo " +
"AND B.OrderNo ='" + nOrderNo + "'";
SqlDataReader dr = cmdSelect.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
txtOrderNo.Text = dr["OrderNo"].ToString();
dtpOrderDate.Value = Convert.ToDateTime(dr["OrderDate"].ToString());
txtCustomerNo.Text = dr["CustomerNo"].ToString();
txtCustomerName.Text = dr["CustomerName"].ToString();
txtCustomerAddress.Text = dr["CustomerAddress"].ToString();
txtPONo.Text = dr["PurchaseOrderNo"].ToString();
cboAgentName.Text = dr["AgentName"].ToString();
txtOrderStatus.Text = dr["Status"].ToString();
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//================================================================================
//================================================================================
private void DisplayOrderDetails(int nOrderNo)
{
OpenConnection();
SqlCommand cmdSelect = new SqlCommand();
cmdSelect.Connection = cn;
cmdSelect.CommandType = CommandType.Text;
cmdSelect.Transaction = trnOrder;
cmdSelect.CommandText =
"SELECT PackagingOutside, Quantity, Unit, ProductNo, ProductName, ProductSize, PackagingInside, " +
"SellingDiscount, SellingPrice, Amount FROM OrderDetails WHERE OrderNo = '"
+ nOrderNo + "'";
SqlDataAdapter daDetail = new SqlDataAdapter();
daDetail.SelectCommand = cmdSelect;
DataSet ds = new DataSet();
daDetail.Fill(ds, "OrderDetails");
grdDetails.DataSource = null;
grdDetails.DataSource = ds.Tables["OrderDetails"];
}
when you use Convert.ToInt16 you will get this exception if value does not consist of an optional sign followed by a sequence of digits (0 through 9)
Do a validation for inputs before proceed like below.
int orderNo;
if (int.TryParse(txtOrderNo.Text, out orderNo))
{
DisplayOrder(orderNo);
DisplayOrderDetails(orderNo);
}
Side Note :
don't share the SqlConnection create new instant when you need it and wrap it with using block like below
using (SqlConnection con = new SqlConnection(connectionString))
{
}
Use SQL Parameters
cmdSelect.CommandText = "SELECT * FROM Orders WHERE OrderNo = #OrderNo";
cmdSelect.Parameters.AddWithValue("#OrderNo", nOrderNo);
This means that the value in txtOrderNo.Text is not considered an integer. You will get this error if your textbox is empty.
Either check that the textbox contains data, or use the TryParse (http://msdn.microsoft.com/en-us/library/f02979c7.aspx) method
There are two things to consider,
Values entered in the textbox should be an integer in the range of 16 bit, if it can be bigger value, then you have to think of going to long, int32 etc.
Validate the textbox using TryParse() which will tell you whether it has valid value entered.

No value given for one or more required parameters.()

I have a problem, when i m login the error is occured that No value given for one or more required parameters.
protected void imgbtn_login_Click(object sender, ImageClickEventArgs e)
{
int UserId = 0;
string str = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=pathto.mdb;Persist Security Info=False;");
OleDbConnection conn = new OleDbConnection(str);
conn.Open();
string query = "select * from Users where LoginName='" + txt_logname.Text + "' and Password='" + txt_pass.Text + "';";
OleDbDataAdapter da=new OleDbDataAdapter(query,conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = new DataTable();
dt = ds.Tables[0];
try
{
UserId = Int32.Parse(dt.Rows[0]["UserId"].ToString());
//btn_LogIn.Text = "Login Succeded";
Response.Redirect("Register.aspx");
}
catch (Exception ex)
{
}
txt_logname.Text = " ";
txt_pass.Text = "";
}
Password is a reserved word. Put it in square brackets [Password]
See Syntax error in INSERT INTO statement

Categories