may be i am tired but any body can say what is the poblem?
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='c:\users\deltagare\documents\visual studio 2015\Projects\School\School\school.mdf';Integrated Security=True");
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'schoolDataSet.student' table. You can move, or remove it, as needed.
//this.studentTableAdapter.Fill(this.schoolDataSet.student);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from student";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
student = new StudentController();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
studentGridView.DataSource = dt;
conn.Close();
}
You have either to use the SqlCommand(string,SqlConnection) overload, or set the SqlCommand.Connection property:
SqlCommand cmd = new SqlCommand("select * from student",conn);
Or
cmd.Connection=conn;
you have to assign the connection to the command before you execute it:
cmd.Connection = conn
Related
I am trying to output the number of depositors which has a total of 5 but when I run the program it outputs only 1. I used stored procedure for this matter. I think something is missing when in the codes below and I don't know. I tried my best to search on the internet.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CountAllUsers();
}
}
protected void CountAllUsers()
{
using (MySqlConnection mycon = new MySqlConnection(constring))
{
mycon.Open();
MySqlCommand cmd = new MySqlCommand("countallusers", mycon);
cmd.CommandType = CommandType.StoredProcedure;
MySqlDataAdapter adx = new MySqlDataAdapter(cmd);
DataSet ds= new DataSet();
adx.Fill(ds);
mycon.Close();
lblDepositors.Text = ds.Tables[0].Rows.Count.ToString();
}
You can use ExecuteScalar to do the query for counting the number of records. Replace TABLE_NAME with your table.
FYI, you don't have to call mycon.Close();, as you apply using statement, when it ends, it will dispose the connection automatically.
Updated:
Added using block for MySqlCommand for Disposable best practice as suggested by #Dai.
protected void CountAllUsers()
{
using (MySqlConnection mycon = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM TABLE_NAME", mycon))
{
cmd.CommandType = CommandType.Text;
mycon.Open();
var count = Convert.ToInt32(cmd.ExecuteScalar());
lblDepositors.Text = count.ToString();
}
}
}
MySqlCommand.ExecuteScalar Method
ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database.
I already solved. Thanks!
protected void CountAllUsers()
{
using (MySqlConnection mycon = new MySqlConnection(constring))
{
mycon.Open();
MySqlCommand cmd = new MySqlCommand("SELECT COUNT(id) as count from depositors_tbl", mycon);
MySqlDataAdapter ada = new MySqlDataAdapter();
DataSet dt = new DataSet();
ada.SelectCommand = cmd;
ada.Fill(dt);
mycon.Close();
lblDepositors.Text = dt.Tables[0].Rows[0]["count"].ToString();
}
}
This is my code :
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
mytable = new DataTable();
mytable.Columns.Add("Customerid");
mytable.Columns.Add("Customername");
mytable.Columns.Add("Contactname");
mytable.Columns.Add("Address");
mytable.Columns.Add("Mobile");
GridView1.DataSource = mytable;
GridView1.DataBind();
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
//SqlCommand cmd = new SqlCommand("select * from Table_3", con);
SqlCommand cmd = new SqlCommand("select1_customer", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(mytable);
GridView1.DataSource = mytable;
GridView1.DataBind();
}
}
Procedure or function 'select1_customer' expects parameter '#Customerid', which was not supplied. it was my error
Your are missing
cmd.Parameters.AddWithValue("#Customerid", required value);
Try,
SqlCommand cmd = new SqlCommand("select1_customer", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Customerid", "value_for_CustomerID");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(mytable);
GridView1.DataSource = mytable;
GridView1.DataBind();
How can I use a rich textbox and some pre-connected string to execute direct Transact-SQL queries and get results into a datagridview?
My GUI form is like this:
I want to use any SQL queries in this rich textbox and get result in data grid view
I using this code for query and fill data gridview
SqlConnection c = new SqlConnection(#"Data Source=.;Initial Catalog=db3;Integrated Security=True");
private void button1_Click(object sender, EventArgs e)
{
SqlDataAdapter a = new SqlDataAdapter("select * from phone", c);
DataTable t = new DataTable();
a.Fill(t);
dataGridView1.DataSource = t;
}
So how do I modify it to this?
SqlConnection c = new SqlConnection(#"Data Source=.;Initial Catalog=db3;Integrated Security=True");
private void button1_Click(object sender, EventArgs e)
{
SqlDataAdapter a = new SqlDataAdapter(Textbox1.Text, c);
DataTable t = new DataTable();
a.Fill(t);
dataGridView1.DataSource = t;
}
I also used Pravin Deshmukh code in another button and get error:
Update 3: used suggested code and got a reference error
private void button3_Click(object sender, EventArgs e)
{
string SqlString = textBox2.Text; // here you can have your user query from textbox
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=.;Initial Catalog=db3;Integrated Security=True"].ConnectionString.ToString());
conn.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(SqlString, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
conn.Close();
cmd.Dispose();
}
Error:
Try this
string SqlString= "your sql query";
SqlConnection conn = new SqlConnection(#"Data Source=.;Initial Catalog=db3;Integrated Security=True");
conn.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(SqlString, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
conn.Close();
cmd.Dispose();
Set datagridview generate columns automatic
EDIT : or
string SqlString= textbox1.Text; // here you can have your user query from textbox
I'm writing a program using C# win forms and SQL Server 2012. In one of my forms I have a combobox a button and a datagrid view. I want the data grid view to be filled every time I change the value in combo box.
This code doesn't work :( (it does not return an error)
private void button1_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(comboBox2.SelectedValue.ToString());
//int idc = 100;
DataSet ptDataset = new DataSet();
string con = ConfigurationManager.ConnectionStrings["secaloFormulaCS"].ToString();
SqlConnection sqlCon = new SqlConnection(con);
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("spDispProductInfo", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#id", id);
sqlCmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
da.Fill(ptDataset);
dataGridView2.DataSource = ptDataset;
sqlCon.Close();
}
Try this.
int id = Convert.ToInt32(comboBox2.SelectedValue.ToString());
//int idc = 100;
DataSet ptDataset = new DataSet();
string con = ConfigurationManager.ConnectionStrings["secaloFormulaCS"].ToString();
SqlConnection sqlCon = new SqlConnection(con);
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("spDispProductInfo", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#id", id);
SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
da.Fill(ptDataset);
dataGridView2.DataSource = ptDataset.Tables[0];
sqlCon.Close();
You must Use the Event of your comboBox clik not the button.
Just try to add this button1_click event to the combobox that you have.
Set your Code in SelectedIndexChanged event Of your comboBox
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ptDataset = new DataSet();
string con = ConfigurationManager.ConnectionStrings["secaloFormulaCS"].ToString();
SqlConnection sqlCon = new SqlConnection(con);
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("spDispProductInfo", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#id", Convert.ToInt32(comboBox2.SelectedValue.ToString()));
sqlCmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
da.Fill(ptDataset);
dataGridView2.DataSource = ptDataset;
sqlCon.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\ExportPagetoPDFinASP.Net\App_Data\abcc.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM cookbook";
cmd.Connection = con;
cmd.ExecuteReader();
}
Not able to fetch data. i don't know what is wrong.
ExecuteReader would return you a DataReader, you need to iterate it and get rows from your command.
You can also use a DataTable to fill the rows from DataReader like:
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
You can have the following code:
using (SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\ExportPagetoPDFinASP.Net\App_Data\abcc.mdf;Integrated Security=True;User Instance=True"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT * FROM cookbook";
cmd.Connection = con;
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
}
}
Consider using using statement with your Connection and Command objects.
You can iterate rows returned from DataReader like:
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0])); //prints first column
}
public string Log(int userResult)
{
string result = "result saved";
using (var conn = new SqlConnection("Data Source=XXXX;InitialCatalog=XXXX;Integrated Security=True"))
{
using (var cmd = new SqlCommand())
{
cmd.CommandText = "dbo.setCalculatorResult";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("RESULT", userResult);
if (conn.State != ConnectionState.Open)
conn.Open();
int rowCount = cmd.ExecuteNonQuery();
if (rowCount == 0)
result = "there was an error";
}
}
return result;
}
and also consider using procs