I have datagridview, that i must fill by 5 tables. I declared SqlCommand and SqlConnection.
After that I use somethine like this:
selCommand.Connection = conn;
dt = new DataTable();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = selCommand;
ad.Fill(dt);
dataGridView1.DataSource = dt;
As a result I have column headers of my query in datagridview, but don't have data.
I tried use this code:
selCommand.Connection = conn;
dt = new DataTable();
SqlDataReader dr = selCommand.ExecuteReader();
dt.Load(dr);
bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
dr.Close();
It was working, but I something change and I can't understand why it does not work.
Try this:
DataTable table = null;
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
try
{
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "SELECT * FROM Something WHERE Id = #Id";
cmd.Parameters.Add(new SqlParameter("#Id", YourValue));
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
table = new DataTable();
adapter.Fill(table);
}
}
catch (Exception ex)
{
//Handle your exception;
}
}
dataGridView1.DataSource = table;
Related
using (SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-IIDC3HF\SQLEXPRESS;Initial Catalog=EmployeeNotifier;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select Name,Salary FROM YOUR TABLE", con);
SqlDataReader dr = cmd.ExecuteReader();
dataGridView1.DataSource = dr;
dataGridView1.DataBind(); // causing problem here
con.Close();
}
I tried this code but this displays an error
Does Not Contain Definition for DataBind
var select =q;
var c = new SqlConnection(#"Your Connection String here ");
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
Now i try this Code and its works really fine for me
Problem is that the datareader must iterate over the an object
try this instead create a custome class to hold your data.like below.
If that is too much trouble use an data adaptor and use DataSets
List<myCustomerCLass> list = new List<myCustomerCLass>();
con.Open();
SqlCommand cmd = new SqlCommand("Select Name,Salary FROM YOUR TABLE", con);
SqlDataReader dr = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
myCustomerCLass test = new myCustomerCLass();
test.property1 = reader["Property1"]
test.property2 = reader["Property2"]
test.property3 = reader["Property3"]
list.add(test);
}
}
reader.Close();
dataGridView1.DataSource = list;
dataGridView1.DataBind(); // causing problem here
con.Close();
I have this code in the server side.
public DataTable DIS(int IID)
{
SqlConnection con = new
SqlConnection(Properties.Settings.Default.ADP_C1ConnectionString);
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from Paper";
cmd.ExecuteNonQuery();
DataTable DT = new DataTable();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(DT);
con.Close();
return DT;
}
I want to make the grid view in the client side take its source from that function like this:
public void dis_data()
{
DataTable DT = mgr.DIS(JouranlIID);
sda.Fill(DT);
dataGridView1.DataSource = DT;
}
How to do that?
well, I've done everything on my behalf just to solve this problem. i'm trying to print the data from my database using grid view in asp.net using c# codes. can anyone tell me whats wrong and how to improve my codes. thank you.
using (MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString))
{
constructor var = new constructor();
con.Open();
string sql = "SELECT first_name,last_name,username,contact_number,address,email FROM user_tbl WHERE user_type='2'";
MySqlCommand cmd = new MySqlCommand(sql, con);
MySqlDataReader reader1 = cmd.ExecuteReader();
reader1.Close();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex)
{
lblresult.Text = "ERROR>>" + ex.Message + "!";
}
finally
{
con.Close();
sql = null;
}
You must fill the DataSet with data like this :
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "TableName");
GridView1.DataSource = ds.Tables["TableName"];
GridView1.DataBind();
You're assigning an empty DataSet to your DataSource, without filling the results of your DataReader into the DataSet/DataTable.
using (MySqlConnection con = new MySqlConnection(""))
{
con.Open();
string sql = "SELECT first_name,last_name,username,contact_number,address,email FROM user_tbl WHERE user_type='2'";
MySqlCommand cmd = new MySqlCommand(sql, con);
try
{
DataTable dt = new DataTable();
using (MySqlDataReader reader1 = cmd.ExecuteReader())
{
dt.Load(reader1);
}
GridView1.DataSource = dt ;
GridView1.DataBind();
}
catch (Exception ex)
{
lblresult.Text = "ERROR>>" + ex.Message + "!";
}
finally
{
con.Close();
sql = null;
}
}
I have a windows application C#
Where i have a datagridview1 where i need to retrieve a multitable data query
When the data is being retrieved from the table,it need to be filtered also at the same time
The problem that i am facing that the data is not been loaded although in the LocalWindows shows
The problem is The data is not being loaded in the datagridview
I can see the data is being loaded in the datagridview through the autos watch in visual studio-i have given the output in the end
what did i do wrong ?
//CODE
private void getData(string selectquery)
{
try
{
// string qryText1 = #"SELECT FEE_HEAD.FEE_HEAD_NAME, FEE_AMOUNT.FEE_HEAD_AMOUNT, FEE_AMOUNT.CLASS_ID FROM FEE_AMOUNT INNER JOIN FEE_HEAD ON FEE_AMOUNT.FEE_HEAD_ID = FEE_HEAD.ID";
SqlConnection con = new SqlConnection(#"Data Source=SRINATH-PC\SQLEXPRESS;Initial Catalog=BFMS;Integrated Security=True");
SqlCommand command = new SqlCommand(selectquery, con);
con.Open();
SqlDataAdapter dataAdapter1 = new SqlDataAdapter();
dataAdapter1.SelectCommand = command;
DataTable dataT = new DataTable();
dataAdapter1.Fill(dataT);
BindingSource bs = new BindingSource();
bs.DataSource = dataT;
dataGridView1.DataSource = bs;
dataAdapter1.Update(dataT);
dataGridView1.Refresh();
con.Close();
}
catch (SqlException ex1)
{
MessageBox.Show(ex1.ToString());
}
}
//LOCAL WATCH VIEW
Count 28 int+ Current {System.Data.DataRowView} object {System.Data.DataRowView}
DataMember "" string
RowCount 29 int
RowHeadersBorderStyle Raised System.Windows.Forms.DataGridViewHeaderBorderStyle
the code is working perfectly
public Form1()
{
InitializeComponent();
string query = "select * from benefitplans";
getData(query);
}
and then
private void getData(string selectquery)
{
try
{
// string qryText1 = #"SELECT FEE_HEAD.FEE_HEAD_NAME, FEE_AMOUNT.FEE_HEAD_AMOUNT, FEE_AMOUNT.CLASS_ID FROM FEE_AMOUNT INNER JOIN FEE_HEAD ON FEE_AMOUNT.FEE_HEAD_ID = FEE_HEAD.ID";
SqlConnection con = new SqlConnection(#"Data Source=392;User id=sa; Password=manage#123;Initial Catalog=Benefit;Pooling=False");
SqlCommand command = new SqlCommand(selectquery, con);
con.Open();
SqlDataAdapter dataAdapter1 = new SqlDataAdapter();
dataAdapter1.SelectCommand = command;
DataTable dataT = new DataTable();
dataAdapter1.Fill(dataT);
BindingSource bs = new BindingSource();
bs.DataSource = dataT;
dataGridView1.DataSource = bs;
dataAdapter1.Update(dataT);
dataGridView1.Refresh();
con.Close();
}
catch (SqlException ex1)
{
MessageBox.Show(ex1.ToString());
}
}
Try replacing these lines
SqlDataAdapter dataAdapter1 = new SqlDataAdapter();
dataAdapter1.SelectCommand = command;
DataTable dataT = new DataTable();
dataAdapter1.Fill(dataT);
BindingSource bs = new BindingSource();
bs.DataSource = dataT;
dataGridView1.DataSource = bs;
dataAdapter1.Update(dataT);
dataGridView1.Refresh();
con.Close();
with
SqlDataAdapter dataAdapter1 = new SqlDataAdapter();
dataAdapter1.SelectCommand = command;
DataSet dataS = new DataSet();
dataAdapter1.Fill(dataS);
dataGridView1.DataSource = dataS;
con.Close();
Hope, this may help.
We need to use display the Columns for the Datagridview using
dataGridView1.Columns[0].Name = "FEE_HEAD_NAME";
ataGridView1.Columns[0].HeaderText = "FEE_HEAD_NAME";
dataGridView1.Columns[0].DataPropertyName = "FEE_HEAD_NAME";
dataGridView1.Columns[1].HeaderText = "FEE_HEAD_AMOUNT";
dataGridView1.Columns[1].Name = "FEE_HEAD_AMOUNT";
dataGridView1.Columns[1].DataPropertyName = "FEE_HEAD_AMOUNT";
Anyways Thanks for the reply everyone
I'm trying to present query results, but I keep getting a blank data grid.
It's like the data itself is not visible
Here is my code:
private void Employee_Report_Load(object sender, EventArgs e)
{
string select = "SELECT * FROM tblEmployee";
Connection c = new Connection();
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
What's wrong with this code?
Here's your code fixed up. Next forget bindingsource
var select = "SELECT * FROM tblEmployee";
var c = new SqlConnection(yourConnectionString); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
String strConnection = Properties.Settings.Default.BooksConnectionString;
SqlConnection con = new SqlConnection(strConnection);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from titles";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;
You don't need bindingSource1
Just set dataGridView1.DataSource = table;
Try binding your DataGridView to the DefaultView of the DataTable:
dataGridView1.DataSource = table.DefaultView;
This is suppose to be the safest and error pron query :
public void Load_Data()
{
using (SqlConnection connection = new SqlConnection(DatabaseServices.connectionString)) //use your connection string here
{
var bindingSource = new BindingSource();
string fetachSlidesRecentSQL = "select top (50) * from dbo.slides order by created_date desc";
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(fetachSlidesRecentSQL, connection))
{
try
{
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
bindingSource.DataSource = table;
recent_slides_grd_view.ReadOnly = true;
recent_slides_grd_view.DataSource = bindingSource;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString(), "ERROR Loading");
}
finally
{
connection.Close();
}
}
}
}
You may get a blank data grid if you set the data Source to a Dataset that you added to the form but is not being used. Set this to None if you are programatically setting your dataSource based on the above codes.
You may try this sample, and always check your Connection String, you can use this example with or with out bindingsource you can load the data to datagridview.
private void Employee_Report_Load(object sender, EventArgs e)
{
var table = new DataTable();
var connection = "ConnectionString";
using (var con = new SqlConnection { ConnectionString = connection })
{
using (var command = new SqlCommand { Connection = con })
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
try
{
command.CommandText = #"SELECT * FROM tblEmployee";
table.Load(command.ExecuteReader());
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
}
you have to add the property Tables to the DataGridView Data Source
dataGridView1.DataSource = table.Tables[0];
if you are using mysql this code you can use.
string con = "SERVER=localhost; user id=root; password=; database=databasename";
private void loaddata()
{
MySqlConnection connect = new MySqlConnection(con);
connect.Open();
try
{
MySqlCommand cmd = connect.CreateCommand();
cmd.CommandText = "SELECT * FROM DATA1";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagrid.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Years late but here's the simplest for others in case.
String connectionString = #"Data Source=LOCALHOST;Initial Catalog=DB;Integrated Security=true";
SqlConnection cnn = new SqlConnection(connectionString);
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblEmployee;", cnn);
DataTable data = new DataTable();
sda.Fill(data);
DataGridView1.DataSource = data;
Using DataSet is not necessary and DataTable should be good enough. SQLCommandBuilder is unnecessary either.
I think this professional way to Write from start, but you can use this code with MySQL bout I think they both are the same:
1/
using System.Data; AND using MySql.Data.MySqlClient;
2/
MySqlConnection con = new MySqlConnection("datasource=172.16.2.104;port=3306;server=localhost;database=DB_Name=root;password=DB_Password;sslmode=none;charset=utf8;");
MySqlCommand cmd = new MySqlCommand();
3/
public void SetCommand(string SQL)
{
cmd.Connection = con;
cmd.CommandText = SQL;
}
private void FillGrid()
{
SetCommand("SELECT * FROM `transport_db`ORDER BY `id` DESC LIMIT 15");
DataTable tbl = new DataTable();
tbl.Load(cmd.ExecuteReader());
dataGridView1.DataSource = tbl;
}
for oracle:
var connString = new ConfigurationBuilder().AddJsonFile("AppSettings.json").Build()["ConnectionString"];
OracleConnection connection = new OracleConnection();
connection.ConnectionString = connString;
connection.Open();
var dataAdapter = new OracleDataAdapter("SELECT * FROM TABLE", connection);
var dataSet = new DataSet();
dataAdapter.Fill(dataSet);