SqlConnection conn1 = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand COMM = new SqlCommand("select Role from Login where User_Name='admin'", conn1);
conn1.Open();
SqlDataReader reader = COMM.ExecuteReader();
while (reader.Read())
{
string s = reader["Role"].ToString();
}
reader.Close();
conn1.Close();
SqlConnection conn = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand comm = new SqlCommand("Select * from FileUpload where UploadedBy='"+NAME+"'",conn);
try
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
if (s.Equals("admin"))
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
if(s.Equals("teacher"))
{
GridView2.DataSource = rdr;
GridView2.DataBind();
}
rdr.Close();
//reader.Close();
}
catch
{
conn.Close();
}
I'm getting error in the below connection saying s does not exist in the current context. How to use the multiple datareaders please help me.
Declare string s out of hte loop
string s;
while (reader.Read())
{
s = reader["Role"].ToString();
}
SqlConnection conn1 = new SqlConnection("Server=ILLUMINATI;" + "Database=DB;Integrated Security= true");
SqlCommand COMM = new SqlCommand("select Role from Login where User_Name='admin'", conn1);
conn1.Open();
SqlDataReader reader = COMM.ExecuteReader();
string s = String.Empty;
while (reader.Read())
s = reader["Role"].ToString();
Related
I have this very short code, and while trying to display data from the database that no all the data is in English, I'm getting in the cmd ???? instead of the actual data. How can I solve this?
SqlConnection conn = new SqlConnection("Data Source = ron\\SQLEXPRESS; Initial Catalog = Cafeteria; Integrated Security = True");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("select * from [Product]", conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0].ToString());
}
}
finally
{
if (rdr != null)
{
rdr.Close();
}
if (conn != null)
{
conn.Close();
}
}
I am faced with the problem that I can not display the table from mysql in the textbox c # I tried this code like this. Help please. Thanks
string cons = "Server=server;DataBase=base;Uid=u0827;pwd=kkda";
MySqlConnection mycon = new MySqlConnection(cons);
mycon.Open();
string con = "SELECT usd FROM curs";
MySqlCommand com = new MySqlCommand(con);
MySqlDataAdapter da = new MySqlDataAdapter(com);
MySqlDataReader DR = com.ExecuteReader();
com.CommandText = #"select TOP 1 usd from curs";
object res = com.ExecuteScalar();
if (res != null) usd.Text = res.ToString();
DR.Close();
mycon.Close();
When running this code, it gives an error -
System.InvalidOperationException: "Connection must be valid and open."
string cons = "Server=ser;DataBase=base;Uid=u082na;pwd=kkdNwijs";
MySqlConnection mycon = new MySqlConnection(cons);
mycon.Open();
string con = "select * from curs";
MySqlCommand com = new MySqlCommand(con, mycon);
MySqlDataReader myReader;
myReader = com.ExecuteReader();
try
{
while (myReader.Read())
{
usd.Text = (myReader.GetString(0));
}
}
finally
{
myReader.Close();
mycon.Close();
}
I retrived values by the use of SqlCommand and SqlReader from column and stored in List<String> and the added to ComboBox(Type:DropDownList) but Eventhough i have deleted Some of this values from database Combobox is still showing it.
I am clearing items befor allocating by
mycombobox.Items.Clear();
It looks as it is not affected by values I retrive every time when the Form gets Loaded.
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
List<string> namesCollection=new List<string>();
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
namesCollection.Add("Select");
if (rdr1.Read()==true)
{
do
{
namesCollection.Add("" + rdr1[0].ToString());
} while (rdr1.Read()) ;
}
else
{
}
foreach(string pname in namesCollection)
cb.Items.Add(pname);
namesCollection.Clear();
cb.SelectedIndex =0;
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
if (rdr1 != null)
rdr1.Close();
if (con1.State == ConnectionState.Open)
con1.Close();
}
Thanks in advance.
Use the DataSource property of the Combobox instead of the adding the items one by one. So your code will be something like the following:
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
List<string> namesCollection = new List<string>();
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
namesCollection.Add("Select");
if (rdr1.Read()==true)
{
do
{
namesCollection.Add("" + rdr1[0].ToString());
} while (rdr1.Read()) ;
}
else
{
}
//Replace this part...
//foreach(string pname in namesCollection)
//cb.Items.Add(pname);
//With this...
cb.DataSource = namesCollection;
cb.SelectedIndex =0;
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
if (rdr1 != null)
rdr1.Close();
if (con1.State == ConnectionState.Open)
con1.Close();
}
There is a similar question here
Hope this helps
Let's say the code to populate the ComboBox is placed in the populate_cb() method
private void populate_cb(){
cb.Items.Clear();
SqlDataReader rdr1 = null;
SqlConnection con1 = null;
SqlCommand cmd1 = null;
try
{
// Open connection to the database
string ConnectionString = #"Data Source=MyPC-PC\SQLEXPRESS;Initial Catalog=DryDB;Integrated Security=True";
con1 = new SqlConnection(ConnectionString);
con1.Open();
cmd1 = new SqlCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT PName from MASTER order by PName";
cmd1.Connection = con1;
rdr1 = cmd1.ExecuteReader();
cb.Items.Add("Select");
while(rdr1.Read())
{
cb.Items.Add(rdr1[0].ToString());
}
cb.SelectedIndex =0;
con1.Close();
}
catch(Exception ex){
// handle exception
}
}//end of populate_cb()
Call populate_cb() method form form_load() and
Call from the place after the deletion process
You need to make sure your deletion process really deletes the records from database!
I am trying to debug the above error. Below is my code.
private SqlConnection SQLConn(string name)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;
return conn;
}
protected void rb2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn = SQLConn("Plastics");
try
{
string selectSQL = "SELECT [Description], [Code], [Change] FROM [plastics]";
SqlCommand cmd = new SqlCommand(selectSQL, conn);
conn.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
}
catch (SqlException Exception)
{
// catch exception
Response.Write("An error occured");
}
finally
{
conn.Close();
}
}
I get an error on GridView1.DataSource = cmd.ExecuteReader();
What must I instantiate?
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
ds.Tables.Add(dt);
string str = "User ID=username;Password=password;Data Source=Test";
SqlConnection conn = new SqlConnection(str);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from table_name";
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if(dt!=null)
{
GridView2.DataSource = dt;
GridView2.DataBind();
}
}
I am new to C# and trying to populate a DropDownList based on a database value. I tried connecting to database as shown below - tested with the statement and it says connected. Can I assume this is correct? Am I on the right track? Also, how do I then select value from the table and fill DropDownList with a field?
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection (
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
connection.Open();
TextBox1.Text = "connected";
}
catch (Exception)
{
TextBox1.Text = " not connected";
}
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection (
"Data Source=.\\SQLEXPRESS;AttachDbFilename=C:customers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
SqlDataReader dReader;
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = CommandType.Text;
cmd.CommandText ="Select distinct [Name] from [Names]" +
" order by [Name] asc";
connection.Open();
dReader = cmd.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
//Names collection is a combo box.
namesCollection.Add(dReader["Name"].ToString());
}
else
{
MessageBox.Show("Data not found");
}
dReader.Close()
TextBox1.Text = "connected";
}
catch (Exception)
{
TextBox1.Text = " not connected";
}
}
Hope that helps................
It's So Much Simple :----
SqlConnection con = new SqlConnection();
DataSet ds = new DataSet();
con.ConnectionString = #"Data Source=TOP7\SQLEXPRESS;Initial Catalog=t1;Persist Security Info=True;User ID=Test;Password=t123";
string query = "Select * from tbl_User";
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandText = query;
con.Open();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(ds);
comboBox1.Items.Clear();
comboBox1.DisplayMember = "UserName";
comboBox1.ValueMember = "UserId";
comboBox1.DataSource = ds.Tables[0];
------------------------------------------------------------------------
using (SqlConnection con = new SqlConnection("Data Source = NIPOON; Initial Catalog = CustomerOrders; Integrated Security = true"))
{
SqlCommand cmd = new SqlCommand("SELECT Name FROM Customer", con);
con.Open();
dropDownList.DataSource = cmd.ExecuteReader();
dropDownList.DataTextField = "Name";
dropDownList.DataValueField = "Name";
dropDownList.DataBind();
}