Error while gathering tablenames from Database c# and asp.net - c#

Database Name is ONLINEEXAM
I have several tables in the db and I want to list some table names starts with letters "set % " in Dropdownlist in asp.net.
I use the following code and I'm getting the error : invalid object name ONLINEEXAM.dbo.sysobjects
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
paperset();
}
}
private void paperset()
{
try
{
string conn = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlCommand cmd = new SqlCommand(
"select * from ONLINEEXAM.dbo.sysobjects where name like 'Set%'", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
ListItem item = new ListItem();
item.Value = dr[0].ToString();
papersetlist.Items.Add(item);
}
dr.Close();
con.Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally { }
}

May be you are running query against a different database, run you query in sql server to check it.
also try this
SqlCommand cmd = new SqlCommand("select * from sys.objects where name like 'Set%'", con);
or use this to get all the tables
select * from sys.tables where name like 'Set%'

Take a look to verify the user ID has access to the sysobjects table.
Assuming you are running SQL2005 or later, you can also look at the INFORMATION_SCHEMA schema and review the TABLES view:
Select TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE
from [database.]INFORMATION_SCHEMA.TABLES

Related

Why my combobox only shows one item? c# mysql

enter image description hereI'm trying to show all my items on a combobox, but when y run my app I only get one item. Can you help me please, here's my code
try
{
MySqlConnection conection = new MySqlConnection("server = 127.0.0.1; database = sistemalaboratorio; Uid = root; pwd =;");
string selectQuery = "SELECT clavemateria FROM materia";
conection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, conection);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read());
{
comboBox1.Items.Add(reader["clavemateria"].ToString());
}
} catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Assuming this read is happening before the page loads the combobox, make sure your materia table has more than 1 record in it.
These queries might usful to count the records in your SQL table in case you dont have direct access using SQL Management studio
SELECT COUNT(*) FROM materia WITH (NOLOCK)
-- NOLOCK here is for testing for this answer: no more, no less
or
SELECT clavemateria, count(*)
FROM materia
GROUP BY clavemateria
Also you can try this:
string qr1 = "select * from materia ";
SqlCommand cmd1 = new SqlCommand(qr1, con);
con.Open();
SqlDataReader dr1 = cmd1.ExecuteReader();
cmbcat.Items.Clear();
while (dr1.Read())
{
cmbcat.Items.Add(new Item(dr1["clavemateria"].ToString(), dr1["clavemateria"].ToString()));
}
con.Close();
Or refer to this example

How can I get combobox ID to return to database

void fill_cbcategoria()
{
try
{
con.Open();
string Query = "select * from Categoria";
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
string categoria = (string)dr.GetString(1);
cbcategoria.Items.Add(categoria);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am using this code to fill my category combobox:
private void btneditar_Click(object sender, EventArgs e)
{
try
{
con.Open();
string Query = "insert into dbPAP.Categoria (id_categoria, categoria)" + "values('" + this.cbcategoria.SelectedValue + this.cbcategoria.SelectedItem + "') ;";
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
MessageBox.Show("Editado com sucesso!");
while (dr.Read())
{
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Now I want to update data to database, but is needed "id_categoria" but I don''t know how can I do it. In Table "Categoria" just got 2 parameters, that's "id_categoria" = 0 and "categoria" = 1. Problem is, can I get "id_categoria" value to update in database using combobox.SelectedItem?
Use executeNonQuery for executing insert command. SqlDataReader is usually used for read data from the database; you can try like the following:
string Query = "insert into dbPAP.Categoria (id_categoria,categoria)values(#selectedVal,#selectedItem)";
SqlCommand createCommand = new SqlCommand(Query, con);
createCommand.Parameters.Add("#selectedVal", SqlDbType.VarChar).Value = this.cbcategoria.SelectedValue;
createCommand.Parameters.Add("#selectedItem", SqlDbType.VarChar).Value = this.cbcategoria.SelectedItem;
createCommand.ExecuteNonQuery();// return 1 in this case if insert success
few suggestions for better understanding:
ExecuteReader : ExecuteReader used for getting the query results as a DataReader object. It is readonly forward only retrieval of records and it uses select command to read through the table from the first to the last.
ExecuteNonQuery : ExecuteNonQuery used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.
You can read more about The purpose of parameterized queries

Can't retrieve data from SqlDataReader in C#

I need to insert values into several tables first I have to retrieve university id from table college and then insert faculty name into table faculty and get generated by SQL Server ID. After all of this I have to insert both ids into an other table.
Problem is that I have to close readers and after I do it I can't retrieve those ids from them so variable where they should be saved is null. Here is my code. How to do it correctly?
Sorry I am new to C# and SQL Server.
// reading data into combobox
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from colege", myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
comboBox1.Items.Add(myReader["name"].ToString());
// Console.WriteLine(myReader["Column2"].ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
myConnection.Close();
private void button1_Click(object sender, EventArgs e)
{
string item = comboBox1.Text.ToString();
// MessageBox.Show(item);
SqlConnection myConnection = new SqlConnection("user id=bogdan_db;" +
"password=1234;server=localhost;" +
"Trusted_Connection=yes;" +
"database=cafedrascience; " +
"connection timeout=30");
try
{
myConnection.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
// reading data into combobox
String colegeid = null;
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from colege where name like'" + item + "'", myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
colegeid = myReader["id"].ToString();
// Console.WriteLine(myReader["Column2"].ToString());
}
myReader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
String facultyid = null;
try
{
SqlDataReader myReader1 = null;
SqlCommand myCommand = new SqlCommand("select * from depart where name like'" + textBox1.Text + "'",
myConnection);
myReader1 = myCommand.ExecuteReader();
while (myReader1.Read())
{
facultyid = myReader1["id"].ToString();
}
myReader1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
SqlCommand myCommand1 = new SqlCommand("INSERT INTO coledge_faculty (coledge_id, faculty_id) " +
"Values ('"+colegeid+"''"+facultyid+"')", myConnection);
myCommand1.ExecuteNonQuery();
// MessageBox.Show(colegeid);
// MessageBox.Show(facultyid);
myConnection.Close();
}
The number one thing I can stress about your code is that you should be using parameterised queries, beyond the obvious risks of SQL Injection, it also protects you against malformed SQL, data truncation through conversion, and it allows you to use cached execution plans.
The next thing to point out is that you should not be using SELECT * in production code, e.g.
SqlCommand myCommand = new SqlCommand("select * from colege where name like'" + item + "'", myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
colegeid = myReader["id"].ToString();
// Console.WriteLine(myReader["Column2"].ToString());
}
Why bother retrieving all the columns of colege from the database, then sending them all over the network if you only care about the column id?
Finally your diagnosis of the problem is not correct:
Problem is that I have to close readers and after I do it, I can't retrieve those ids from them, so variable where they should be saved is null
If you assign the string variable colegeid a value you have retrieved from a data reader, it will not be null after you have closed the reader, it will retain the value you assigned. The most likely reason the variable is null is because your reader returns no rows so you never assign it a value.
Now, rant over, I will actually answer your question. You are massively over complicating the issue, you do not need to retrieve the values into your application tier only to insert them to another table, you can do this all in a single query in your database:
INSERT INTO coledge_faculty (coledge_id, faculty_id)
SELECT c.id, d.id
FROM depart AS d
CROSS JOIN colege AS c
WHERE d.Name = #Depart
AND c.Name = #Colege;
Then it would just be a case of calling this SQL from C#:
string item = comboBox1.Text.ToString();
string connectionString = "user id=bogdan_db; password=1234;server=localhost; Trusted_Connection=yes; database=cafedrascience; connection timeout=30";
string sql = #"INSERT INTO coledge_faculty (coledge_id, faculty_id)
SELECT c.id, d.id
FROM depart AS d
CROSS JOIN colege AS c
WHERE d.Name = #Depart
AND c.Name = #Colege;";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#Colege", SqlDbType.VarChar, 50).Value = item;
command.Parameters.Add("#Depart", SqlDbType.VarChar, 50).Value = textBox1.Text;
connection.Open();
command.ExecuteNonQuery();
}
It is usually a good idea to use using blocks with objects that implement IDisposable, this will ensure the resources are freed up when you are done with them (Don't confuse this with not being able to reuse the connection, .NET has connection pooling in the background so it will reuse connections for you, you shouldn't keep your SqlConnection object open available in case you need to use it again).
On another unrelated note, I also think you are too liberal with try/catch blocks, or at least not dealing with the exception properly, using this one as an example:
try
{
myConnection.Open();
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
If myConnection.Open() does throw an error, you still carry on with the method. You will carry on until you get to here:
SqlCommand myCommand = new SqlCommand("select * from colege where name like'" + item + "'", myConnection);
myReader = myCommand.ExecuteReader();
Where you will get another exception, something along the lines of the command requiring an open and available SqlConnection, so you go to the exception.
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Again you don't exit the method, but carry on, and you will get the same error later when you try and use the connection again. Again the method carries on and you will use the closed connection a third time to try and insert two variables that were never assigned because exceptions were thrown into your database. Fine, use try catch blocks, but do something meaningful with the exception and exit the method.
private void BtnAdd_Click(object sender, EventArgs e)
{
//con.Open();
cmd = new SqlCommand("INSERT INTO TBL_STORE VALUES (N'"+txt_store_name.Text.Trim()+"',N'"+txt_store_adress.Text.Trim()+"',N'"+txt_store_mobile_1.Text.Trim()+"',N'"+txt_store_mobile_2.Text.Trim()+"',N'"+txt_store_Manger.Text.Trim()+"',N'"+txt_store_Details.Text.Trim()+"')");
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.AddWithValue("#store_name", txt_store_name.Text.Trim());
cmd.Parameters.AddWithValue("#store_adress", txt_store_adress.Text.Trim());
cmd.Parameters.AddWithValue("#store_mobile_1", txt_store_mobile_1.Text.Trim());
cmd.Parameters.AddWithValue("#store_mobile_2", txt_store_mobile_2.Text.Trim());
cmd.Parameters.AddWithValue("#store_manger", txt_store_Manger.Text.Trim());
cmd.Parameters.AddWithValue("#store_details", txt_store_Details.Text.Trim());
cmd.Parameters.AddWithValue("#Id_store", txt_store_number.Text.Trim());
con.Close();
lbl_store.Text="insert is sucess";
//cmd.Parameters.Add("#store_name", SqlDbType.NVarChar, 50).Value = txt_store_name.Text.Trim();
}

How to get database value to label filtered by combobox

I have a combobox connected to a database which shows initials of employees. Now if I select an initial, I want a label to show the name of the employee that belongs to this initial.
What's wrong with my code?
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(constr);
SqlCommand cmd1 = new SqlCommand("SELECT Prename FROM Employee WHERE Initials=#Initials", conn);
cmd1.Parameters.Add(new SqlParameter("#Initials", comboBox1.SelectedIndex.ToString()));
SqlDataReader PrenameReader;
try
{
conn.Open();
PrenameReader = cmd1.ExecuteReader();
while (PrenameReader.Read())
{
string sPrename = PrenameReader["Prename"].ToString();
lblPrename.Text = sPrename;
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks in advance!
this is your problem I think
cmd1.Parameters.Add(new SqlParameter("#Initials", comboBox1.SelectedIndex.ToString()));
change it to
cmd1.Parameters.Add(new SqlParameter("#Initials", comboBox1.SelectedValue.ToString()));
Or
cmd1.Parameters.Add(new SqlParameter("#Initials", comboBox1.SelectedText);
whichever gives proper Initials.
Also I am not sure how many Values you will get from that query but if you want the first result either use Top 1 in you select query or don't read all Data as it will only get the last record's value

Ado.Net Fill Grid By Logged in User

I need to fill a gridview with records according to the currently logged in user. My stored procedure asks for one parameter, the ID of the user. I want that parameter to be the currently logged in user but i cant figure out how to accomplish this.
My stored Procedure to grab the records:
#cnt_ID int
AS
BEGIN
SELECT TOP (100) PERCENT dbo.vtCursusPlanning.cur_CursusID AS CursusID, dbo.vtCursusPlanning.cur_Omschrijving AS Omschrijving, CONVERT(varchar,
dbo.vtData.dat_Datum, 100) AS Datum, CONVERT(varchar, dbo.vtData.dat_Start, 100) AS DStart, CONVERT(varchar, dbo.vtData.dat_Stop, 100) AS DStop,
dbo.vtContactPersonen.cnt_Initialen AS Username
FROM dbo.vtData INNER JOIN
dbo.vtCursusPlanning ON dbo.vtData.cur_FK = dbo.vtCursusPlanning.cur_CursusID INNER JOIN
dbo.vtContactPersonen ON dbo.vtCursusPlanning.cnt_FK = dbo.vtContactPersonen.cnt_ID INNER JOIN
dbo.vtCursusCursisten ON dbo.vtData.cur_FK = dbo.vtCursusCursisten.cst_fk
WHERE (dbo.vtContactPersonen.cnt_ID = #cnt_ID) AND (NOT (dbo.vtCursusCursisten.cst_fk IS NULL)) AND (NOT (dbo.vtCursusPlanning.cur_Project IS NULL))
ORDER BY DStart
END
And my attempt to fill the gridview with my C# code.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
GridView1.DataKeyNames = new string[] { "#cnt_ID" };
string connectionString = ConfigurationManager.ConnectionStrings["KRIS-Planning"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("spOffice2010Evaluaties", conn);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add("#cnt_ID", SqlDbType.Int);
comm.Parameters["#cnt_ID"].Value = UserID;
try
{
conn.Open();
reader = comm.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
reader.Close();
}
catch (Exception ex)
{
dbErrorLabel.Text = Convert.ToString(ex);
}
finally
{
conn.Close();
}
}
}
Try this one instead;
string UserId = HttpContext.Current.User.Identity.Name;

Categories

Resources