I'm trying to fill a combo box on from load from a database, I'm getting the error "Invalid object name 'POOL'"
Form load event to populate dropdown on form load
private void FRMAddTeam_Load(object sender, EventArgs e)
{
if (CMBBXPool.Items.Count > 0)
CMBBXPool.Items.Clear();
Database.CLSDB DatabaseClass = new Database.CLSDB();
DatabaseClass.FillDropDownList();
}
This is the code in my database connection class
public void FillDropDownList()
{
string PoolName = "";
Team.FRMAddTeam TeamAdd = new Team.FRMAddTeam();
SqlConnection conn = GetConnection();
string selStmt = "SELECT [Name] FROM dbo.TBL_pool";
SqlCommand selCmd = new SqlCommand(selStmt, conn);
try
{
conn.Open();
SqlDataReader reader = selCmd.ExecuteReader();
while (reader.Read())
{
PoolName = reader["Name"].ToString();
TeamAdd.addPoolItem(PoolName);
}
}
catch (SqlException ex) { throw ex; }
finally { conn.Close(); }
return;
}
Code to add the pool name
public void addPoolItem(string PoolName)
{
CMBBXPool.Items.Add(PoolName);
}
Any help is much appreciated
Your code needs to be:
public void FillDropDownList(Team.FRMAddTeam TeamAdd)
{
string PoolName = "";
SqlConnection conn = GetConnection();
string selStmt = "SELECT [Name] FROM dbo.TBL_pool";
SqlCommand selCmd = new SqlCommand(selStmt, conn);
try
{
conn.Open();
SqlDataReader reader = selCmd.ExecuteReader();
while (reader.Read())
{
PoolName = reader["Name"].ToString();
TeamAdd.addPoolItem(PoolName);
}
}
catch (SqlException ex) { throw ex; }
finally { conn.Close(); }
return;
}
You call it from your form like this:
DatabaseClass.FillDropDownList(this);
This will work, however it is strongly advised to change the implementation of your database class and remove tight coupling with GUI.
It is WRONG to fill your GUI from database class - instead of that, you should return data from your database class and bind your data to GUI in the GUI class.
http://en.wikipedia.org/wiki/Loose_coupling
http://en.wikipedia.org/wiki/Object_orgy
http://en.wikipedia.org/wiki/Separation_of_concerns
Sounds like you dont have table Pool.Are you sure its there?
Log into your SQL management studio and use query analyzer to run the same command.
There could be many reasons for that If your schema is different or do you have permission to access that table ? or are you checking the right database ?
UPDATE:
You should try using SELECT [Name] FROM dbo.TBL_Pool
Related
First post here. I'm trying to create a website that fetches data from an Oracle database and returns some tables. I was able to connect my database fine and made a DataConnector that returns a list of CodeDesc objects. My main problem right now is simply displaying that data to the screen, preferably in the form of a drop down list but I'm using a GridView for now.
Here's my front end:
protected void Button1_Click(object sender, EventArgs e)
{
DataConnector dc = new DataConnector();
GridView2.DataSource = dc.getCodeTypes();
GridView2.DataBind();
}
When I click the button, nothing is generated and the debugger only says "Exception thrown: 'System.ArgumentException' in Oracle.DataAccess.dll" Any help would be appreciated. This is my first time doing web development and it's been a struggle to get even this far. I'm using Visual Studio 2015
Back End:
//Create datatable to get info from db & return results
public List<CodeDesc> getCodeTypes()
{
try
{
OracleConnection con = new OracleConnection(connString);
con.Open();
string query = "select id, descr from code_desc where code_type_id = 0";
// Create the OracleCommand
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
// Execute command, create OracleDataReader object
OracleDataReader reader = cmd.ExecuteReader();
List<CodeDesc> L = new List<CodeDesc>();
while (reader.Read())
{
CodeDesc c = new CodeDesc();
c.id = reader.GetInt32(0);
c.description = reader.GetString(1);
L.Add(c);
}
// Clean up
reader.Dispose();
cmd.Dispose();
con.Dispose();
System.Diagnostics.Debug.WriteLine(L);
return L;
}
catch (Exception ex)
{
// catch clause here...
}
}
CodeDesc:
public class CodeDesc
{
public int id { get; set; }
public string description { get; set; }
}
Any help would be great.
You never set the query string to the CommandText property of the OracleCommand. Of course this can only result in an exception when you try to execute your command.
Said that, remember that every disposable object should be enclosed in a using statement. This is very important in case of exceptions because the correct closing and disposing is executed automatically exiting from the using block
public List<CodeDesc> getCodeTypes()
{
try
{
List<CodeDesc> L = new List<CodeDesc>();
string query = "select id, descr from code_desc where code_type_id = 0";
using(OracleConnection con = new OracleConnection(connString))
using(OracleCommand cmd = new OracleCommand(query, con))
{
con.Open();
// Execute command, create OracleDataReader object
using(OracleDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
CodeDesc c = new CodeDesc();
c.id = reader.GetInt32(0);
c.description = reader.GetString(1);
L.Add(c);
}
}
}
System.Diagnostics.Debug.WriteLine(L);
return L;
}
I want to get mysql from one form by clicking a button and then it goes to another form and show the data on a textbox separating by commas.
Here is my code:
private void button3_Click(object sender, EventArgs e)
{
connection = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog='yadb';username=root;password=");
//command = connection.CreateCommand();
string query = "SELECT `tpno` FROM `member` WHERE `electorate_cluster`='"+comboBox1.Text+"'";
command = new MySqlCommand(query, connection);
try
{
connection.Open();
//MySqlDataAdapter mda = new MySqlDataAdapter("SELECT `tpno` FROM `member` ", connection);
reader = command.ExecuteReader();
while (reader.Read())
{
//string s = "tpno";
sms sm = new sms();
sm.mobno.Text = reader.GetString("tpno".Split(","));
}
}
catch (Exception)
{
throw;
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
In here I used mysql database to store data and mobno.text means the 2nd form textbox
Btw I am new to C#
you can have parameterized constructor for your second form...and pass data what you need from frist form and make sure your paramterized constructor is calling default constructor.
Something like this
public class sm : Form
{
public sm()
{
IntializeComponent();
}
public sm(string data):this()
{
//Assign the data wherever you want
}
}
In first form button click event do this
while (reader.Read())
{
//string s = "tpno";
sms sm = new sms(reader.GetString("tpno".Split(",")));
sm.Show();
}
I tried to get data from SQL Server (2 tables: Famille and Compte) into 2 comboboxes in the Form_Load().
But as you see the result, it works with the 1st combobox, but the 2nd it shows System.Data.SqlClient.SqlDataReader
This is the Code
private void Tresorerie_Load(object sender, EventArgs e)
{
conn = new SqlConnection(connstring);
conn.Open();
String queryCompte = "select NomCom from Compte";
String queryFamille = "select NomFam from Famille";
commCompte = new SqlCommand(queryCompte, conn);
commFamille = new SqlCommand(queryFamille, conn);
try
{
//Compte
commCompte.CommandType = CommandType.Text;
dreaderCompte = commCompte.ExecuteReader();
while (dreaderCompte.Read())
{
queryCompte = dreaderCompte[0].ToString();
TreComBoxCompte.Items.Add(queryCompte);
}
}
catch (Exception)
{
MessageBox.Show("Problem with load Compte");
}
finally
{
dreaderCompte.Close();
}
try
{
//Famille
commFamille.CommandType = CommandType.Text;
dreaderFamille = commFamille.ExecuteReader();
while (dreaderFamille.Read())
{
queryFamille = dreaderFamille[0].ToString();
TreComBoxFamille.Items.Add(dreaderFamille);
}
}
catch (Exception)
{
MessageBox.Show("Problem with load Famille");
}
finally
{
dreaderFamille.Close();
}
conn.Close();
}
For second combobox you are adding your datareader dreaderFamille:
TreComBoxFamille.Items.Add(dreaderFamille);
while you should add queryFamille:
queryFamille = dreaderFamille[0].ToString();
TreComBoxFamille.Items.Add(queryFamille);
If you pay attention to item texts in your ComboBox you will guess the problem and when you look at code, you will see your guess is true.
for 2nd comboxbox, you are using wrong object to add
TreComBoxFamille.Items.Add(queryFamille);
You should do it like this:
while (dreaderFamille.Read())
{
queryFamille = dreaderFamille[0].ToString();
TreComBoxFamille.Items.Add(queryFamille);
}
I'm trying to get these textboxes to show data from a database, i'm able to show the data but everytime I try to update it won't save. Here's what i've done
private void ClubRecord_Load(object sender, EventArgs e)
{
try
{
sConnection = "Provider = Microsoft.Jet.OLEDB.4.0;" + "Data Source = Eastern_Property_Maintenance.mdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
sql = "SELECT * FROM Club ORDER BY CompanyName, CompanyAddress, CompanyPhone;";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbreader = dbCmd.ExecuteReader();
while (dbreader.Read())
{
string CompanyName = dbreader["CompanyName"].ToString();
string CompanyAddress = dbreader["CompanyAddress"].ToString();
string CompanyPhone = dbreader["CompanyPhone"].ToString();
txtCompanyName.Text = CompanyName;
txtCompanyAddress.Text = CompanyAddress;
txtCompanyPhone.Text = CompanyPhone;
}
dbreader.Close();
// dbConn.Close();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
private void btnConfirmChanges_Click(object sender, EventArgs e)
{
string companyName = txtCompanyName.Text;
string companyAddress = txtCompanyAddress.Text;
string companyPhone = txtCompanyPhone.Text;
string Update = "UPDATE [Club] SET [CompanyName]= #CompanyName,[CompanyAddress]=#CompanyAddress,[CompanyPhone]=#CompanyPhone";
OleDbCommand dbcmd = new OleDbCommand(Update, dbConn);
dbCmd.Parameters.AddWithValue("#CompanyName", companyName);
dbCmd.Parameters.AddWithValue("#CompanyAddress", companyAddress);
dbCmd.Parameters.AddWithValue("#CompanyPhone", companyPhone);
try
{
dbCmd.ExecuteNonQuery();
MessageBox.Show("Update Complete");
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
Any help would be greatly appreciated thanks.
It is a subtle typo error, but I think that there is something to learn here, so I want to give a full answer:
You create a command called dbcmd
OleDbCommand dbcmd = new OleDbCommand(Update, dbConn);
but then you fill the parameter collection of a different command dbCmd and executes this one.
dbCmd.Parameters.AddWithValue("#CompanyName", companyName);
dbCmd.Parameters.AddWithValue("#CompanyAddress", companyAddress);
dbCmd.Parameters.AddWithValue("#CompanyPhone", companyPhone);
C# is case sensitive, so the twos are not the same command, but how does it lead to the failed update is worth to look at.
You have declared a global OleDbCommand variable named dbCmd and this variable is still set to the SELECT query used to load the textboxes. So, when you call ExecuteNonQuery it does not update anything.
You could fix the problem simply changing all the references in the updated code from dbCmd to dbcmd. But, the lesson to learn here is, when possible avoid to use global variables.
The Connection is another example of a global variable and this is worst because it is left open after the initial form load. Don't do that. Connectiosn keep valuable system resources locked and thus should be closed immediately after usage applying the using statement pattern
private void btnConfirmChanges_Click(object sender, EventArgs e)
{
string companyName = txtCompanyName.Text;
string companyAddress = txtCompanyAddress.Text;
string companyPhone = txtCompanyPhone.Text;
string Update = #"UPDATE [Club] SET [CompanyName]= #CompanyName,
[CompanyAddress]=#CompanyAddress,
[CompanyPhone]=#CompanyPhone"; // A where here should be mandatory
using(OleDbConnection dbConn = new OleDbConnection(aGlobalConnectionStringWouldBeSafeHere))
using(OleDbCommand dbcmd = new OleDbCommand(Update, dbConn))
{
dbcmd.Parameters.AddWithValue("#CompanyName", companyName);
dbcmd.Parameters.AddWithValue("#CompanyAddress", companyAddress);
dbcmd.Parameters.AddWithValue("#CompanyPhone", companyPhone);
try
{
dbcmd.ExecuteNonQuery();
MessageBox.Show("Update Complete");
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
}
By the way, I hope that your table contains only one record because without a WHERE clause you update every record present with the values of your textboxes.
I have an asp.net wizard control in my web application I am calling a stored procedure from code behind to insert data into database. Executing the proc in SSMS works fine and I had gotten this block to work once before and made changes (i unfortunately cannot remember which changes i made). My problem is that when the next button is clicked no errors are thrown and also no data is written to the database. I have tested by adding exception into the cnx2 try block and the exceptions were thrown so I know the code is executing to the place I want it to but it is still not inserting. Any help is appreciated Thank you. And please if there is any information i can add that may help let me know
protected void onNextButtonClick(object sender, EventArgs e)
{
if (Wizard1.ActiveStepIndex.Equals(1))
{
page1Submit();
}
else if (Wizard1.ActiveStepIndex.Equals(2))
{
page2Submit();
}
else if (Wizard1.ActiveStepIndex.Equals(3))
{
page3Submit();
}
else if (Wizard1.ActiveStepIndex.Equals(8))
{
page8submit();
}
}
protected void page1Submit()
{
string hispanic;
if (cbIsHispanic.Checked)
{
hispanic = "1";
}
else
{
hispanic = "0";
}
bool newReport = true;
SqlConnection cnx = new SqlConnection(server);
SqlCommand cmd = new SqlCommand("[ReportCheckExists]", cnx);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#reportNumber", dReportNumber.Text.ToString());
try
{
cnx.Open();
int rowCount = Convert.ToInt32(cmd.ExecuteScalar());
cnx.Close();
if (rowCount > 0)
{
newReport = false;
}
}
catch (Exception ex)
{
throw new Exception("Error executing MyProcedureName.", ex);
}
if (newReport)
{
SqlConnection cnx2 = new SqlConnection(server);
SqlCommand cmd2 = new SqlCommand("[NewReport]", cnx2);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue("#reportNumber", dReportNumber.Text.ToString());
try
{
cnx.Open();
cmd.ExecuteNonQuery();
cnx.Close();
}
catch (Exception ex)
{
throw new Exception("Error executing MyProcedureName.", ex);
}
}
else
{
string strJavaScript = "<script language = javascript type=text/Javascript> alert('That report number already exists. If you need to modify a report select it from the main menu or enter the report number again.')</script>";
this.Page.RegisterClientScriptBlock("Key4", strJavaScript);
Wizard1.ActiveStepIndex = 0;
}
}
It's probably because you are executing the cmd command, and not cmd2 in your second try catch block