how to pass ds from sql class to form class
in my form class
sqlCls floor = new sqlCls();
floor.getByFloor(floorNo);
reportFormDataGridView.DataSource = ds.Tables[0]; ******
in sql class . floor method
public DataSet getByFloor(int floorNo)
{
DataSet ds = new DataSet();
SqlConnection conn = connectionCls.openConnection();
SqlCommand com = new SqlCommand("select * from table where floorsNo = " + floorNo, conn);
SqlDataAdapter SE_ADAPTAR = new SqlDataAdapter(com);
SE_ADAPTAR.Fill(ds);
conn.Close();
return ds;
}
GridViews can take a DataSet as the DataSource just fine, no need to use a table.
Just do this:
sqlCls floor = new sqlCls();
var ds = floor.getByFloor(floorNo);
reportFormDataGridView.DataSource = ds;
You have a SQL Injection vulnerability in your code. Please consider using SQL parameters instead of unsanitized input.
So in your case it would be:
public DataSet getByFloor(int floorNo)
{
DataSet ds = new DataSet();
SqlConnection conn = connectionCls.openConnection();
SqlCommand com = new SqlCommand("select * from table where floorsNo = #floorsNo", conn);
com.Parameters.AddWithValue("#floorsNo", floorNo);
using(SqlDataAdapter SE_ADAPTAR = new SqlDataAdapter(com))
{
SE_ADAPTAR.Fill(ds);
conn.Close();
}
return ds;
}
SqlDataAdapter implements the IDisposable interface so you can wrap it in a using block to automatically dispose of resources when execution flow leaves the scope.
Related
I'm passing a query and parameter from a WinForm to a database class. The
The code on the Form looks like this:
string selectedComp = "CPSI";
string catsQuery = "SELECT id, category, old_value, old_desc, new_value, new_desc, reference1, reference2 FROM masterfiles.xref WHERE company_name = '#company' ORDER BY category, old_value";
Db categoriesData = new Db();
dgvCategories.DataSource = categoriesData.GetData(catsQuery, selectedComp);
And in my database class my code to populate the datatable/set is this:
public DataTable GetData(string selectQuery, string selectedComp)
{
NpgsqlConnection conn = new NpgsqlConnection(connString);
DataSet ds = new DataSet();
NpgsqlCommand cmd = new NpgsqlCommand(selectQuery, conn);
cmd.Parameters.Add(new NpgsqlParameter("#company", selectedComp));
//cmd.Parameters.AddWithValue("#company", selectedComp);
//cmd.Parameters.Add("#company", NpgsqlDbType.Text);
//cmd.Parameters["#company"].Value = selectedComp;
try
{
conn.Open();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(selectQuery, conn);
conn.Close();
da.Fill(ds);
return ds.Tables[0];
}
}
But putting a breakpoint at NpgsqlDataAdapter da = new NpgsqlDataAdapter(selectQuery, conn);, selecctQuery hasn't changed - the '#company' is still in the query.
What am I missing?
The root problem is that you're passing the query to the data adapter instead of the command. Change
NpgsqlDataAdapter da = new NpgsqlDataAdapter(selectQuery, conn);
to
NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
I would also use using to dispose of all objects, and don't close the connection until the dataset is filled:
using(NpgsqlConnection conn = new NpgsqlConnection(connString))
using(NpgsqlCommand cmd = new NpgsqlCommand(selectQuery, conn))
{
cmd.Parameters.Add(new NpgsqlParameter("company", selectedComp));
conn.Open();
using(NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
da.Fill(ds);
}
conn.Close();
return ds.Tables[0];
}
I want to keep reading data process separate in a class and pass that data to the a Form to display in the DataGridView as data source. I can build row by row in a List and then pass that to the Form but I am wondering if there is simple way of just passing complete data set to the form as parameter?
Here is my code to build the dataset:
class DAL_ProjectMaster
{
// List<string> ProjectList = new List<string>();
OleDbConnection DBcon;
OleDbCommand DBcmd;
OleDbDataAdapter DBadp;
ConString constr = new ConString();
public void GetProjectMaster()
{
string connectString = constr.GetConString();
DBcon = new OleDbConnection(connectString);
DBcmd = new OleDbCommand("select * from ProjectMaster", DBcon);
DBcon.Open();
DBadp = new OleDbDataAdapter(DBcmd);
DataSet ds = new DataSet();
DBadp.Fill(ds);
}
}
}
I would like to pass ds to the Form where I can use as data source for DataGridview like this:
dataGridView1.DataSource = ds.Tables[0];
change GetProjectMaster to return DataSet
public DataSet GetProjectMaster()
{
DataSet ds = new DataSet();
string connectString = constr.GetConString();
using( var con = new OleDbConnection(connectString))
using( var cmd = new OleDbCommand("select * from ProjectMaster", con))
{
con.Open();
using(var adp = new OleDbDataAdapter(cmd))
{
adp.Fill(ds);
}
}
return ds;
}
now you can call above method as
DAL_ProjectMaster dal = new DAL_ProjectMaster();
dataGridView1.DataSource = dal.GetProjectMaster().Tables[0];
You can use session
//for assign
DataSet ds = new DataSet();
Session.Add("Name", ds);
// for retrieve
ds = (DataSet)Session["Name"];
I need to get a database values to the p_cat combo box .....but i cannot pass the dataset inside the query..
class Datatbl_Class1
{
DataSet ds = new DataSet();
public DataSet filldata(string q)
{
string myconnection = "datasource=localhost;port=3306;username = root; password = 12345V";
MySqlConnection con = new MySqlConnection(myconnection);
MySqlCommand cmd = new MySqlCommand(q, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}
}
Select_int_Class1 s4 = new Select_int_Class1();
string q = "SELECT Sup_ID FROM gtec_computer.supplier WHERE Sup_Name='" +p_cmb_sup.Text+ "'";
string ww = "Sup_ID";
int t = s4.select_val_int(q, ww);
DataSet n = new DataSet();
Datatbl_Class1 dt = new Datatbl_Class1();
string Query = "SELECT Cat_ID FROM gtec_computer.supplier_detail WHERE Sup_Id="+t+" ";
n = dt.filldata(Query)
DataSet ds = new DataSet();
string myconnection = "datasource=localhost;port=3306;username = root; password = 12345V";
MySqlConnection con = new MySqlConnection(myconnection);
string q1 = "SELECT cat_Name FROM gtec_computer.category WHERE Cat_ID= " + n + " ";
MySqlCommand cmd = new MySqlCommand(q1, con);
MySqlDataAdapter da1 = new MySqlDataAdapter(cmd);
da1.Fill(ds);
p_cat.DataSource = ds;
You should be able to via parameter to the function call in the class... However, by building your command strings, you would be wide open for SQL-injection. Look into parameterized queries. Now, back to your original code and an alternative implementation...
class Datatbl_Class1
{
public DataSet filldata(string q )
{
string myconnection = "datasource=localhost;port=3306;username = root; password = 12345V";
MySqlConnection con = new MySqlConnection(myconnection);
MySqlCommand cmd = new MySqlCommand(q, con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ReturnThisOne = new DataSet();
da.Fill(ReturnThisOne);
return ReturnThisOne;
}
}
Just dont make the "ds" as a property of the class. Just create a new instance of a dataset within your method. It will be a pointer anyhow. Fill that and return the pointer to the calling source as you already are doing with your "n = dt.filldata(Query)". Yes, the function is no longer using the data table, but since it's reference is being returned, then the "n" location that is calling it will retain it. It won't get released to garbage collection until the function that "n" is in gets released.
Again, look into parameters to prevent sql-injection. But this should get you going.
I want to select all customer information where customerid = the selected customerid stored in the combo box and show the result in datagridview I tried this code but the gridview doesnot show result.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
int id = Convert.ToInt32(comboBox1.SelectedValue);
string cmdstring=string.Format("select *from customers where customer_id={0}",id);
SqlCommand cmd = new SqlCommand(cmdstring,con);
//cmd.Parameters.AddWithValue("#id",id);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//da.Fill(ds, "customers");
//dataGridView1.DataSource = ds.Tables["customers"];
con.Open();
SqlDataReader red = cmd.ExecuteReader();
con.Close();
dataGridView1.DataSource = red;
button = new DataGridViewButtonColumn();
button.HeaderText = "edit";
button.Tag = ds.Tables["customers"].Columns["customer_id"];
dataGridView1.Columns.Add(button);
}
you could always make a DataBase Class and if you need to refactor this Class to pass in Connection String or read Connection string from .Config File you can use this as a template to get started plus it's a lot cleaner
Notice that I am returning a DataTable you can use this if you like just a suggestion
public class ClassDataManagement
{
public DataTable GetData(string sqlcmdString, string connString)
{
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
if you want to use DataSet instead of DataTable replace where i have DataTable with
or change the method to return a DataSet like this below
public DataSet GetData(string sqlcmdString, string connString)
{
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
after returning the ds you will need to bind it like this
dataGridView1.DataSource = ds;
dataGridView1.DataBind();
I'm fairly certain that you're not getting any data because you're closing the connection before binding, and because you're using an incompatible type as your data source:
con.Close();
dataGridView1.DataSource = red;
Set the data source prior to closing the connection, or at least be sure to populate the data (for data readers, the data are populated as you enumerate). Additionally, DataGridView.DataSource indicates that it must use one of four interfaces: IList, IListSource, IBindingList, and IBindingListSource. SqlDataReader does not support these. I recommend reading DataAdapters and DataReaders, as this outlines some of the features that are for populating this kind of control.
I can't understand what I am doing wrong, I can't seem to SELECT with a prepared statement. However I can INSERT with a prepared statement.
MySqlCommand cmd = new MySqlCommand("SELECT * FROM code_post WHERE name = ?postRequired LIMIT 1", dbcon);
cmd.Parameters.Add(new MySqlParameter("?postRequired", requestString));
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
cmd.fill(ds, "result");
try {
thisBlog = ds.Tables["result"].Rows[0];
} catch {
invalid();
return;
}
Any advice on this would be greatly appreciated!
To fill a DataSet you will need a DataAdapter.
Try this:
MySqlCommand cmd = new MySqlCommand("SELECT * FROM code_post WHERE name = ?postRequired LIMIT 1", dbcon);
cmd.Parameters.Add(new MySqlParameter("?postRequired", requestString));
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
MySqlDataAdapter dAdap = new MySqlDataAdapter();
dAdap.SelectCommand = cmd;
dAdap.Fill(ds, "result");
try {
thisBlog = ds.Tables["result"].Rows[0];
} catch {
invalid();
return;
}
You need to use SqlDataAdapter
DataAdapter represents a set of data commands and a database connection that are used to fill the DataSet and update a SQL Server database.
The SqlDataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source
Check the following syntax:
private static DataSet SelectRows(DataSet dataset,
string connectionString,string queryString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(
queryString, connection);
adapter.Fill(dataset);
return dataset;
}
}