my method is:
{
conn.Open();
SqlCommand cmd = new SqlCommand
("select BusinessEntityID from Person.Person order by'BusinessEntityID' ASC", conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr["BusinessEntityID"]);
}
conn.Close();
}
but that's not what I want. I have a class. update, insert, and delete list that also includes methods. a draw method of the ComboBox here I write data in the form side of the DataSource of the ComboBox I can I take it? In my system, every time the form on the side, I am forced to open and close connections.
for example, I take like DataGridView data
class side
public DataTable list()
{
SqlDataAdapter da = new SqlDataAdapter
("select * from HumanResources.Employee", OpenConnection());
DataTable dt = new DataTable();
DataSet ds = new DataSet();
da.Fill(dt);
CloseConnection();
return dt;
}
form side
dataGridView1.DataSource = data.list();
Related
I want to return a list of data from database, I pass params to a stored procedure, it then returns results to a list
List<DataDetail> FetchData(GenRequest Request)
{
List<DataDetail> details = new List<DataDetail>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
// con.Open();
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("sp_Gen", con);
con.Open();
cmd.Parameters.AddWithValue("#ForcedATMAmt", ForcedATMAmt);
cmd.Parameters.AddWithValue("#OthersValue", OthersValue);
con.Close();
cmd.ExecuteReader();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
DataDetailobj = new DataDetail();
obj.AdditionalPremium = dr["AdditionalPremium"].ToString();
obj.ATMLimit = dr["ATMLimit"].ToString();
details.Add(obj);
}
}
return details
}
I tried the approach in the code above but when I hover over dr, the dr.HasRows is false. any way I can return the data to a list without DataRows?
Generally speaking, when working with a database connection your order of operations is:
Open the database connection
Run your queries/commands
Close the database connection
In your case, it should go something like this:
con.Open()
SqlCommand cmd = new SqlCommand("sp_Gen", con);
// add parameters
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
// run your code to get values from da
con.Close()
As a side note, I don't believe you need to call cmd.ExecuteReader(); yourself, but that SqlDataAdapter.Fill() will execute the command for you.
I want to return records on the basis of two parameters, EmployeeNo and Password. What i mean is that when a user enter his/her credentials like EmployeeNo and Password then first program check if its present in the database or not. But i have a problem with the datatable. Datatable has no rows. Following is my code, which seems Okay to me but i have no idea why its not working. Here is my code
protected void btnLogin_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(Base.GetConnection))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM TableUserProfile WHERE UserEmpNum=#UserEmpNum and UserPassword=#UserPassword", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#UserEmpNum", tbEmpNumber.Text);
cmd.Parameters.AddWithValue("#UserPassword", tbPassword.Text);
con.Open();
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
ad.Fill(dt);
cmd.ExecuteNonQuery();
if (dt.Rows.Count != 0)
{
if (cbRememberLogin.Checked)
{
Response.Cookies["UEmpNo"].Value = tbEmpNumber.Text;
Response.Cookies["UPass"].Value = tbPassword.Text;
Response.Cookies["UEmpNo"].Expires = DateTime.Now.AddDays(15);
Response.Cookies["UPass"].Expires = DateTime.Now.AddDays(15);
}
else
{
Response.Cookies["UEmpNo"].Expires = DateTime.Now.AddDays(-1);
Response.Cookies["UPass"].Expires = DateTime.Now.AddDays(-1);
}
Session["UserEmployee"] = tbEmpNumber.Text;
Response.Redirect("~/UserProfile.aspx");
}
}
}
When i put my program on a debug mode, it retrieve nothing, Here is the pic
Here is my Database Table
Try this code
MySqlDataAdapter sda = new MySqlDataAdapter();
cmd.Connection = con;
sda.SelectCommand = cmd;
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count > 0 && dt != null)
{
gvr_rkit.DataSource = dt;
gvr_rkit.DataBind();
}
SqlDataAdapter is a part of the ADO.NET Data Provider. SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object .The SqlDataAdapter works with the DataSet to provide a disconnected data retrieval mechanism.
he SelectCommand property of the SqlDataAdapter is a Command object that retrieves data from the data source. The Fill method of the DataAdapter is used to populate a DataSet with the results of the SelectCommand . Fill method takes as its arguments a DataSet to be populated, and a DataTable object , or the name of the DataTable to be filled with the rows returned from the SelectCommand
I have a dropdownlist and a gridview.. Dropdown list contains the list of the tables I have in my database. What I want is, when I select a particular table name from the dropdownlist, I want all the columns and data inside that particular table display inside the gridview.
This is my code...
Code for displaying the list of tables inside the dropdown is success.. But to bind the columns and data inside the gridview is not success..
Please Help me...
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT table_name FROM INFORMATION_SCHEMA.TABLES", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "table_name";
DropDownList1.DataValueField = "table_name";
DropDownList1.DataBind();
con.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.columns where table_name='+ DropDownList1.selecteditem.text +'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
//+DropDownList1.selecteditem.text +
GridView1.DataBind();
con.Close();
}
}
This is a bad idea on several levels. First you are wide open to SQL injection. Second, you are giving everyone full view access to every column and row of every table.
But the reason you are not getting data is because the select string does not make sense. It should look like this
"SELECT * FROM INFORMATION_SCHEMA.columns where table_name='" + DropDownList1.SelectedValue + "'"
But this is how a proper sql connection should look like.
//create a new datatable
DataTable dt = new DataTable();
//create the string that hold the query including token
string query = "SELECT * FROM INFORMATION_SCHEMA.columns where table_name = #TableName";
//create a new database connection
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandType = CommandType.Text;
//replace the token with the correct value
command.Parameters.Add("#TableName", SqlDbType.VarChar).Value = DropDownList1.SelectedValue;
//open the connection
connection.Open();
//load the data of the select into the datatable
dt.Load(command.ExecuteReader());
//bind the datatable to the gridview
GridView1.DataSource = dt;
GridView1.DataBind();
//but you can also skip the datatable and bind directly to the gridview
GridView1.DataSource = command.ExecuteReader();
GridView1.DataBind();
}
i have to search data from the text box in datagrid using c#
My code is
private void button_Search_Click(object sender, EventArgs e)
{
sqlcon.Open();
//DataSet ds15 = new DataSet();
DataTable dt= new DataTable();
SqlDataAdapter adpt = new SqlDataAdapter("Select ColumName from TableName where Field like '%{0}%'", comboBox_Search.Text);
adpt.Fill(dt);//datatable to catch the fields from the database
dataGridView1.DataSource = dt;
Getting error Arguement exception was unhandled
I want to search through combo box
there is no constructor match your parameters on SqlDataAdapter
SqlDataAdapter adpt = new SqlDataAdapter(string.Format("Select ColumName from TableName where Field like '%{0}%'",
comboBox_Search.Text), sqlcon);
Query every time to the database is not a preferable approach. Instead take a BindingSource object and fill the source once. Then use BindingSource.Filter property to get relevant result set and bind the result set to grid.
Have a look at this and and this link.
Also, to fix your issue you can try like this:
....
sqlcon.Open();
string query = string.Format("Select ColumName from TableName where Field like '%{0}%'", comboBox_Search.Text);
SqlCommand cm = new SqlCommand(query, sqlcon);
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(dt);//datatable to catch the fields from the database
dataGridView1.DataSource = dt;
....
How does the SqlDataAdapter know where to get the result from?
You are not initializing the constructor for your SqlDataAdapter properly. The first argument is the full select statement and the second argument is your connection string.
SqlDataAdapter adpt = new SqlDataAdapter(string.Format("Select ColumName from atm_status where Table like '%{0}%'", comboBox_Search.Text), sqlcon);
private void txt_Searchque_TextChanged(object sender, EventArgs e)
{
string connector_string = "datasource = localhost;port=3306;username=root;password=;";
MySqlConnection sqlcon = new MySqlConnection(connector_string);
sqlcon.Open();
string query = string.Format("Select * from oep.quiz where que like '%{0}%'", txt_Searchque.Text);
MySqlCommand cmd = new MySqlCommand(query, sqlcon);
MySqlDataAdapter adpt = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
adpt.Fill(dt);
dataGridView1.DataSource = dt;
}
I searched some posts but still cant get it work.
I have a window application written in C#, Here I bind the datagridview to my database:
public static DataSet GetDataSet(string sql)
{
using (SqlConnection cn = new SqlConnection(constr))
{
SqlDataAdapter da = new SqlDataAdapter(sql, cn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
and I bind the datagridview in another class:
string sql = "select Amount, Price, Description from myTable";
ds = DbHelper.GetDataSet(sql);
dataGridView2.DataSource = ds.Tables[0];
I created a button for user to update the database after they edit the datagridview:
string sql = "select Amount, Price, Description from myTable";
DbHelper.UpdateDataSet(sql, ds);
MessageBox.Show("done");
public static void UpdateDataSet(string sql, DataSet ds)
{
using (SqlConnection cn = new SqlConnection(constr))
{
SqlDataAdapter da = new SqlDataAdapter(sql, cn);
da.Update(ds);
}
}
Here is the error, occurs at the line da.Update(ds);:
Update requires a valid UpdateCommand when passed DataRow collection with modified rows.
Thanks for help.
EDIT
I can get it work with this:
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
da.UpdateCommand = commandBuilder.GetUpdateCommand();
But only when I show the key in the datagridview as well, otherwise:
Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
How to overcome this if I dont want to show the key in datagridview?
SqlCommandBuilder needs the Primary Key to update the field. You can still load the key to the DataGridView, but hide the column.