I am trying to display a table data of my db in a DataGridView.here is my code
private void button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("Data Source=SHIRWANIPC;" +
"Initial Catalog=TEST DATABASE;" + "Integrated Security=True");
myConnection.Open();
SqlCommand objcmd = new SqlCommand("SELECT * FROM Customer", myConnection);
SqlDataAdapter adp = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
//adp.Fill(dt);
DataGridView.DataSource = adp.Fill(dt);
}
The code is not giving any error now but but it dosent display the data from my table in my grid ?
You are using class name instead of object (instance) name of DataGridView, check in the html what is ID/name of DataGridView, It is probably Win Forms and you do not have DataBind method there. DataBind method is defined for GridView for ASP.net. Find more about DataGridView here.
DataGridViewObject.DataSource = adp.Fill(dt);
this is the answer to my quetion , hope it helps others who are new to this
SqlConnection myConnection = new SqlConnection("Data Source=SHIRWANIPC;" + "Initial Catalog=TEST DATABASE;" + "Integrated Security=True");
myConnection.Open();
SqlCommand objcmd = new SqlCommand("SELECT * FROM Customer", myConnection);
//objcmd.ExecuteNonQuery();
SqlDataAdapter adp = new SqlDataAdapter(objcmd);
DataTable dt = new DataTable();
adp.Fill(dt);
//MessageBox.Show(dt.ToString());
dataGridView1.DataSource = dt;
Create an instance of DatagridView:
DataGridView dview = new DataGridView();
....
dview.DataSource = adp.Fill(dt);
dview.DataBind();
You are directly accessing DataGridView properties and tryingto add data to the class. You need to create and an instance of a DataGridView first. Then assign the datable to the object.
Than bind the data to the DataGridView, otherwise the data is not bound to the control and will not be displayed.
DataGridView view = new DataGridView();
dview.DataSource = adp.Fill(dt);
dview.DataBind();
You are not exectuting the query
myConnection.Open();
SqlCommand objcmd = new SqlCommand("SELECT * FROM Customer", myConnection);
DataTable dt = new DataTable(); using
(SqlDataReader sqlDataReader = objcmd.ExecuteReader())
{
dt.Load(sqlDataReader);
sqlDataReader.Close();
}
DataGridView dataGridView1 = new DataGridView();
dataGridView1.DataSource = dt;
Related
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();
}
Here what I have done
I make a GridView and choose the data key name as id and in the basis of id I want to show the DetailsView. Here the CS code
using (SqlConnection con1 = new SqlConnection("Data Source= IA; initial catalog =aip; integrated Security=true;"))
{
con1.Open();
SqlCommand cmd = new SqlCommand("select * from Pm where user_id='" +(String)Session["uid"]+ "'", con1);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
con1.Close();
}
Then I make DetailsView method on SelectedIndexChanged:
But it is showing empty DetailsView in output on selecting 'Select' option
here is the code image
enter image description here
You have used the DataSet not DataTable. So you could either do this:
da.Fill(ds,"tbl");
GridView1.DataSource = ds.Tables[0];
Or use a DataTable instead:
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
Also you should always use parameterized queries to avoid SQL Injection. Something like this:
SqlCommand cmd = new SqlCommand("select * from Pm where user_id=#userId", con1);
cmd.Parameters.AddWithValue("#userId", (String)Session["uid"]);
Also have a look at this: Can we stop using AddWithValue() already?
you need to set DataTable instead of DataSet
GridView1.DataSource = ds.Tables["Pm"];
#PIYUSH Itspk please check query and replace
SqlCommand cmd = new SqlCommand("select * from Pm where user_id=" +Session["uid"].tostring()+ ", con1);
i think its help you if any other query please notify me
I need some help because I've been trying different things but nothing seems to work properly the question itself is the one below.
How can I bind data to a grid-view in Visual Studio 2013 with a local SQL Server database using the code behind C# ?
Here is the C# I'm trying:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Guillermo\Desktop\HorsensHospital\App_Data\HospitalDB.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
GridView1.DataSource = ds;
GridView1.DataBind();
cmd.ExecuteNonQuery();
con.Close();
}
You just assing your empty DataSet to your Gridview's DataSource.
You need to use .Fill method fo fill your DataSet of SqlDataAdapter. You don't need to use ExecuteNonQuery. This method just executes your query. It doesn't return any data or something as a result.
Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataAdapter. You don't need to .Close() your database connections and objects when you use it.
using(SqlConnection con = new SqlConnection(conString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]";
using(SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
You should use statement like this :
when you use SqlDataAdapter you should fill an dataset with Fill Method
then set the DataSource Properties Of GridView
SqlCommand cmd = new SqlCommand("SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
You have missed Fill method to fill your your dataset that is why i think you are not able to display gridview.
Fill Method is very Improtant method Bcoz whatever your query is returning that should be filled into your dataset & then that dataset is binded by your Gridiview
Hope this will help you
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Guillermo\Desktop\HorsensHospital\App_Data\HospitalDB.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [Task_temp_name], [Task_templatesID] FROM [Task_templates]", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
cmd.ExecuteNonQuery();
con.Close();
}
Note : You need to create your connection string in Web.Config. Bcoz If you have created your connection string there then you will not need to create that again. Once creating there you will just need to call that from the Web.config
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringNameFromWebConfig"].ConnectionString);
This is the syntax for calling connection string from web.config
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 am working on a winforms project and i have this following code in the Form_Load method. But it doesnt work. Can anyone help me?
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Sella.Properties.Settings.Database1ConnectionString1"].ConnectionString);
// A SqlCommand object is used to execute the SQL commands.
SqlCommand scmd = new SqlCommand("Select * From CustCalls", conn);
// A SqlDataAdapter uses the SqlCommand object to fill a DataSet.
SqlDataAdapter sda = new SqlDataAdapter(scmd);
// Create and Fill a new DataSet.
DataSet ds = new DataSet();
sda.Fill(ds);
dataGridView1.DataSource = ds;
Try sourcing directly to the table in the dataset:
dataGridView1.DataSource = ds.Tables[0];
SqlDataAdapter sda = new SqlDataAdapter(scmd, conn);
dataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;