get data from database and display it in gridview (asp.net) - c#

I have a database (SQL server) and I added it into my webpage project but the problem is I cannot display the data in a gridview.
Here is my code:
string query;
SqlCommand SqlCommand;
SqlDataReader reader;
int sindex=DropDownList1.SelectedIndex+1;
int hindex =DropDownList3.SelectedIndex+1;
SqlDataAdapter adapter = new SqlDataAdapter();
//Open the connection to db
conn.Open();
query = string.Format("select * from table where clumn='"+s+"' ", s);
SqlCommand = new SqlCommand(query, conn);
adapter.SelectCommand = new SqlCommand(query, conn);
reader = SqlCommand.ExecuteReader();
GridView2.DataSource = reader;
GridView2.DataBind();

Change this
query = string.Format("select * from table where clumn='"+s+"' ", s);
to this
query = string.Format("select * from table where clumn='{0}' ", s);

Use SqlParameters instead of manipulating a string as you are doing now.
Also, use using statement to dispose objects correctly.
Don't use select * because it will affect performance, only select the columns needed.
Here an example of your code, modified:
using (SqlConnection conn = new SqlConnection(yourConnectionString))
{
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandType = CommandType.Text;
command.CommandText = "select column, column2 from table where column=#column";
command.Parameters.Add(new SqlParameter("column", SqlDbType.VarChar, 50));
command.Parameters["column"].Value = yourColumnValue;
conn.Open();
using (SqlDataReader sdr = sco.ExecuteReader())
{
GridView2.DataSource = sdr;
GridView2.DataBind();
}
}

better use SqlDatadapter:
DataTable dt = new DataTable();
...
using (SqlDataAdapter a = new SqlDataAdapter( new SqlCommand(query, conn)))
{
GridView2.DataSource =a.Fill(dt).AsDataView();
}

Related

How Can I add more then one query in one connection (Visual Studio C# to PostgreSQL)

I add data to database
NpgsqlConnection conn1 = new NpgsqlConnection("Server=localhost;Port=5432;Database=test;User Id=postgres;Password=postgres;");
conn.Open();
NpgsqlCommand comm = new NpgsqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = "SELECT * FROM test";
NpgsqlDataReader dr = comm.ExecuteReader();
if (dr.HasRows)
{
dt.Load(dr);
dataGridView1.DataSource = dt;
}
comm.Dispose();
conn.Close();
so far everything is fine
but I want to add more then one query in one connection
e.g.
comm.CommandText = "SELECT * FROM test";
NpgsqlDataReader dr = comm.ExecuteReader();
// some code for view data in dataGridView1
comm.CommandText = "SELECT * FROM test1";
NpgsqlDataReader dr = comm.ExecuteReader();
// and some code for view data in dataGridView2
but I can't
or maybe use transaction but I don't know how to use it.
Easier life when you use a dataadapter:
var conn = "Server=localhost;Port=5432;Database=test;User Id=postgres;Password=postgres;"
var da = new NpgsqlDataAdapter("SELECT * FROM one", conn);
var dt = new DataTable();
da.Fill(dt);
grid1.DataSource = dt;
da = new NpgsqlDataAdapter("SELECT * FROM two", conn);
dt = new DataTable();
da.Fill(dt);
grid2.DataSource = dt;

Displaying results of query to Oracle database in dataGrid

I am struggling to make my dataGrid viev results of query. Connection with database is fine. Here is sample of my code:
using (OracleConnection conn = new OracleConnection())
{
conn.ConnectionString = "properConnectionString"
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select * FROM WORKERS";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
using (OracleDataAdapter orclDataAdapter = new OracleDataAdapter(cmd))
{
DataTable dt = new DataTable();
orclDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
Assuming that your call to the Oracle database is actually returning data, you're missing the databind statement on the gridview. Add this:
dataGridView1.DataBind();
place it right after the dataGridView1.DataSource = dt; line of code.

OleDb Exception in c# “No value given for one or more required parameters.” while trying to Select Data from Access database

I have the following code:
public DataTable opencon(PAL.property objpal)
{
string query = "Select UserId,Firstname,UserType from TBL_USER_LOGIN where Username=#username and Password=#password and Status=1";
OleDbCommand objcmd = new OleDbCommand();
objcmd.CommandText = query;
objcmd.Connection = oldbcon;
oldbcon.Open();
objcmd.Parameters.Add("#username", OleDbType.VarChar).Value = objpal.username;
objcmd.Parameters.Add("#password", OleDbType.VarChar).Value = objpal.Password;
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter(objcmd);
adp.Fill(dt);
return dt;
}
Here I want to fetch some values from the table according to a condition,
but when I run this code it shows the following error:
Even though I passed the correct parameters value in #username and #password. How can I resolve this error? Please help.
Try This:
public DataTable opencon(PAL.property objpal)
{
string query = "Select UserId,Firstname,UserType from TBL_USER_LOGIN where Username=? and Password=? and Status=1";
OleDbCommand objcmd = new OleDbCommand();
objcmd.CommandText = query;
objcmd.Connection = oldbcon;
oldbcon.Open();
objcmd.Parameters.Add("#username", OleDbType.VarChar).Value = objpal.username;
objcmd.Parameters.Add("#password", OleDbType.VarChar).Value = objpal.Password;
DataTable dt = new DataTable();
OleDbDataAdapter adp = new OleDbDataAdapter(objcmd);
adp.Fill(dt);
return dt;
}
Try This
string query = "Select [UserId],[Firstname],[UserType] from [TBL_USER_LOGIN] where [Username]=? and [Password]=? and [Status]=1";

Populate textbox with selected items from database

private void fillProduct() {
SqlConnection conn = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
conn.Open();
string query = "Select prodID from product";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0) {
cmbPCode.DataSource = dt;
cmbPCode.DisplayMember = "prodID";
cmbPCode.ValueMember = "prodID";
}
private void cmbPCode_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
con.Open();
string query = "Select * from product where prodID = '"+cmbPCode.Text+"'".ToString();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read()) {
tbdc.Text = dr["prodDescription"].ToString();
}
}
i am having trouble with getting my items from the database according to the selected index i get this error
Conversion failed when converting the varchar value
'System.Data.DataRowView' to data type int
can someone please help me how to convert SqlDataReader to String. because i notice that when i retrieve a column with varchar/string datatype i am not having this kind error but if i retrieve a column with int datatype i get this error.
Replace This:
string query = "Select * from product where prodID = '"+cmbPCode.Text+
"'".ToString();
With This:
string query = "Select * from product where prodID = "+cmbPCode.Text;
Suggestion: Your query is open to SQL Injection i would suggest you to use parameterised queries to avoid them.
Using Parameterised Queries:
string query = "Select * from product where prodID = #ID";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID",cmbPCode.Text);

Object reference not set to an instance of an object (don't know what I should do)

Here is the error:
Exception Details: System.NullReferenceException: Object reference not
set to an instance of an object.
and it stops here: con.Open();
and here is the code:
SqlConnection con = new SqlConnection(DBHelper.connection);
SqlCommand com = new SqlCommand();
con = com.Connection;
con.Open();
com.CommandType = CommandType.Text;
com.CommandText = "select catname,catdescription,photo from category where catid=" + catselectddl.SelectedValue ;
SqlDataReader dr= com.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
DataRow drr;
drr=dt.Rows[0];
con.Close();
the error:
Line 19: SqlCommand com = new SqlCommand();
Line 20: con = com.Connection;
Line 21: con.Open(); // here the error
Line 22: com.CommandType = CommandType.Text;
Line 23: com.CommandText = "select catname,catdescription,photo from category where catid=" + catselectddl.SelectedValue
Third line is wrong. It should be
com.Connection = con;
You need to change this line (com.Connection is null at that point):
con = com.Connection;
to this:
com.Connection = con;
You're assigning the connection in the wrong order. You should be assigning the connection you create on the first line to the SqlCommand, not assigning the connection of the SqlCommand (which hasn't been created yet) to the SqlConnection variable con you created earlier.
SqlConnection con = new SqlConnection(DBHelper.connection);
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con
You should also check your connection state to make sure it opened successfully before executing your command.
Try this:
SqlConnection con = new SqlConnection(DBHelper.connection);
SqlCommand com = con.CreateCommand();
con.Open();
com.CommandType = CommandType.Text;
com.CommandText = "select catname,catdescription,photo from category where catid=" + catselectddl.SelectedValue ;
SqlDataReader dr= com.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
DataRow drr;
drr=dt.Rows[0];
con.Close();
You were actually trying to create a connection from a command - the command needs to be assigned a connection, not vice versa.
I would also suggest the "using" syntax which I like, that also takes care of disposal for the command and the connection.
using (SqlConnection con = new SqlConnection(DBHelper.connection))
{
using(SqlCommand com = con.CreateCommand())
{
con.Open();
com.CommandType = CommandType.Text;
com.CommandText = "select catname,catdescription,photo from category where catid=" + catselectddl.SelectedValue ;
SqlDataReader dr= com.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
DataRow drr;
drr=dt.Rows[0];
}
}
"select catname,catdescription,photo from category where catid=" + catselectddl.SelectedValue
On a side note:
This type of SQL Script, if turned into a habit, WILL open doors to SQL-Injection; and I assume no developer likes this type of flaw...

Categories