Loading DataGridView from Stored Procedure - c#

I'm having problems loading a stored procedure into a DataGridView. I've searched for an answer, however my code looks similar to every answer I've found. The stored procedure runs in another DataGridView I've added where I included it as a fixed datasource. I'm new to C#. Can anyone see where I am going wrong?
private void Form1_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
SqlConnection myConn = new SqlConnection("Data Source=SERVER-SQL1;Initial Catalog=OPSystem;Integrated Security=True");
myConn.Open();
SqlCommand myCmd = new SqlCommand("spCustomers", myConn);
myCmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(myCmd);
da.Fill(dt);
dataGridView1.DataSource = da;
}

You can't bind to a SqlDataAdapter. You need to bind to the DataTable.
DataTable dt = new DataTable();
SqlConnection myConn = new SqlConnection("Data Source=SERVER-SQL1;Initial Catalog=OPSystem;Integrated Security=True");
myConn.Open();
SqlCommand myCmd = new SqlCommand("spCustomers", myConn);
myCmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(myCmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataBind();
For context, the SqlDataAdapter:
Represents a set of data commands and a database connection that are
used to fill the DataSet and update a SQL Server database. This class
cannot be inherited.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter(v=vs.110).aspx

private BindingSource bindingSource1 = new BindingSource();
DataTable dt = new DataTable();
SqlConnection myConn = new SqlConnection("Data Source=SERVER-SQL1;Initial Catalog=OPSystem;Integrated Security=True");
myConn.Open();
SqlCommand myCmd = new SqlCommand("spCustomers", myConn);
myCmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(myCmd);
da.Fill(dt);
bindingSource1.DataSource = dt;
dataGridView1.DataSource = bindingSource1;
Try BindingSource

Related

how to use 2 DataGridViews in one form (c#)?

I want to use two DataGridViews in this form, which will receive their information from two different tables in one database. But when I run the program, both DataGridViews only display the second table information.
private void Ring_Load(object sender, EventArgs e)
{
showdata();
showmedal();
}
void showdata()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM Ring", con);
da.SelectCommand = cmd;
dt.Clear();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Columns[3].Visible = false;
}
void showmedal()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM medal", con);
da.SelectCommand = cmd;
dt.Clear();
da.Fill(dt);
dataGridView2.DataSource = dt;
}
private void Ring_Load(object sender, EventArgs e)
{
showdata();
showmedal();
}
void showdata()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM Ring", con);
da.SelectCommand = cmd;
using(DataTable dt = new DataTable())
{
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.DataBind();
dataGridView1.Columns[3].Visible = false;
}
}
void showmedal()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM medal", con);
da.SelectCommand = cmd;
using(DataTable dt = new DataTable())
{
da.Fill(dt);
dataGridView2.DataSource = dt;
dataGridView2.DataBind();
}
}
Try this
private void Ring_Load(object sender, EventArgs e)
{
showdata();
showmedal();
}
void showdata()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM Ring", con);
da.SelectCommand = cmd;
dt.Clear();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Columns[3].Visible = false;
}
void showmedal()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM medal", con);
da.SelectCommand = cmd;
dt.Clear();
dt = new DataTable();
da.Fill(dt);
dataGridView2.DataSource = dt;
}
You seem to be reusing da and dt. Reusing da is no problem, but reusing dt is. When you assign dt to DataGridView.DataSource, the data is NOT copied! So in the end, both DataGridViews will be using the same DataTable object, that holds the data from the second table (medal).
You could try this:
private void Ring_Load(object sender, EventArgs e)
{
showdata();
showmedal();
}
void showdata()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM Ring", con);
da.SelectCommand = cmd;
DataTable dt1 = new DataTable();
da.Fill(dt1);
dataGridView1.DataSource = dt1;
dataGridView1.Columns[3].Visible = false;
}
void showmedal()
{
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("SELECT Number,Weight,Ring_Id FROM medal", con);
da.SelectCommand = cmd;
DataTable dt2 = new DataTable();
da.Fill(dt2);
dataGridView2.DataSource = dt2;
}
Edit: renamed the local DataTable variables for clarity.

Assign query result into a session

i want assign result into a session
c# code
protected void BindData()
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-677TN4G\SQLEXPRESS;Initial Catalog=homework;Persist Security Info=True;User ID=sa;Password=123456");
DataSet ds = new DataSet();
DataTable FromTable = new DataTable();
con.Open();
string cmdstr = "Select CourseName from Staff where FacultyNumber=#idd";
SqlCommand cmd = new SqlCommand(cmdstr, con);
cmd.Parameters.AddWithValue("#idd", Session["id"].ToString());
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
DataList1.DataSource = ds.Tables[0];
DataList1.DataBind();
}
so how i can do it i try to do
Session["id"] = cmdstr.Text;
but it not work
i do it like this but not work
I do it like this
protected void BindData()
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-677TN4G\SQLEXPRESS;Initial Catalog=homework;Persist Security Info=True;User ID=sa;Password=123456");
DataSet ds = new DataSet();
DataTable FromTable = new DataTable();
con.Open();
string cmdstr = "Select CourseName from Staff where FacultyNumber=#idd";
SqlCommand cmd = new SqlCommand(cmdstr, con);
cmd.Parameters.AddWithValue("#idd", Session["id"].ToString());
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
DataList1.DataSource = ds.Tables[0];
Session.Add("Staff", ds.Tables[0]);
DataList1.DataBind();
Label1.Visible = true;
Label1.Text = "Course Name is : " + Session["Staff"].ToString();
}
and the output is
Course Name is : Table
not the selected value
In your case the result is a DataTable no problem you can store this DataTable to the session as well. Let staffData be the DataTable that you are populating from the database,
Session.Add("Staff", staffData); // Adding datatable to the session
In your case you are using ds is used as a DataSet and you are accessing ds.Tables[0] to bind the grid. in this case you can use something like: Session.Add("Staff", ds.Tables[0]);.
Later you may come up with another question that how can I retrieve this DataTable from the session, Here I'm adding the answer for that as well.
DataList1.DataSource = (DataTable)Session["Staff"];

c# how to use Combobox.Value for a From Clause in a Sql query

Please can you assist me in a very weird request
I am building a form to represent a table in a datagridview.
I want to change the data that is bound to the datagridview when i select a different value in a combobox. I bound the event to a button.
i get an error when i run the code:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll Additional information: Syntax error in query. Incomplete query clause.
the code i have is as follows.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand("Select * From #name ", con);
cmd.Parameters.AddWithValue("#name", comboBox1.SelectedValue);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
This code will help you:
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ",comboBox1.Text), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
you can not pass table name as parameter. you can build sql based on your value selection in your combobox. replace your code with this code and check.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ",comboBox1.SelectedValue), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
If you use Data Bound Items then use comboBox1.SelectedValue. If you use Unbound Mode then use comboBox1.SelectedItem.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
//OleDbCommand cmd = new OleDbCommand("Select * From " + comboBox1.SelectedValue.ToString(), con);
OleDbCommand cmd = new OleDbCommand("Select * From " + comboBox1.SelectedItem.ToString(), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
But not advice this way. You can use stored Procedure.
Try This:
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
string tableName = comboBox1.SelectedValue;
var builder = new SqlCommandBuilder();
string escapedTableName = builder.QuoteIdentifier(tableName);
OleDbCommand cmd = new OleDbCommand("Select * From " + escapedTableName , con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}

Filling the grid View with more than 1 table?

I have the following code
SqlConnection con = new SqlConnection();
con.ConnectionString=#"Data Source=RITESH-PC\SQLEXPRESS;database=master;Integrated Security=true";
con.Open();
SqlDataAdapter adp = new SqlDataAdapter("Select * from Employee2",con);
SqlDataAdapter adp1 = new SqlDataAdapter("Select * from employee1", con);
DataSet dst=new DataSet();
DataTable dt= new DataTable();
DataTable dt1 = new DataTable();
Now please tell me how to show both the tables in 1 Gridview..
Try this simple code ..
DataSet dataSet = new DataSet();
using (SqlConnection connection =
new SqlConnection(connectionString))
{
connection.Open();
SqlDataAdapter adapter =
new SqlDataAdapter ("select t1.* ,t2.* from table1 t1,table2 t2 ", connection);
adapter.Fill(dataSet);
MyGridview1.DataSource=dataSet;
MyGridview1.DataBind();
}
U can also make use of Merge function to combine 2 DataTable like this:
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=RITESH-PC\SQLEXPRESS;database=master;Integrated Security=true";
con.Open();
SqlDataAdapter adp = new SqlDataAdapter("Select * from Employee2", con);
SqlDataAdapter adp1 = new SqlDataAdapter("Select * from employee1", con);
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
adp.Fill(dt);
adp1.Fill(dt1);
//After merge u will get merge result in dt.
dt.Merge(dt1);
While merging DataTable make sure schema must match.

how to access all table field in datagrid of WPF in ADO.net

I have use following code to access database,
but my datagrid do not display any records.
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=Sanket;Integrated Security=True;Pooling=False");
DataSet ds = new DataSet();
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM std", conn);
da.Fill(ds);
myDataGrid.ItemsSource = ds.Tables[0].DefaultView;

Categories

Resources