I have a textbox that I'm using to search a customer from my database.
this is my code :
DataView dv = new DataView(tabSearchCustomer);
dv.RowFilter = string.Format("CONVERT({0},System.String) LIKE '%{1}%'", "ID", txtboxSearchCustomer.Text);
dgvCustomers.DataSource = dv;
dgvCustomers.DataSource = dv only shows the new data , it doesn't replace it in the dgv.
I want that my dgv will updated with the new data I was searched (replace the old data in the dgv) , how can I do that ?
My dgv before the search :
My dgv after the search :
public static DataTable ExecuteQuery(string storedProcedure, SqlParameter[] parameters)
{
using (SqlConnection sqlConnection = new SqlConnection(DLLConfig.GetDataBaseConnection()))
{
DataTable dataTable = new DataTable();
SqlCommand sqlCommand = new SqlCommand(storedProcedure, sqlConnection);
sqlCommand.CommandTimeout = 0;
sqlCommand.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter param in parameters)
{
sqlCommand.Parameters.Add(param);
}
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCommand);
sqlAdapter.Fill(dataTable);
SqlConnection.ClearAllPools();
return dataTable;
}
}
Usage:
dataGridView1.DataSource = ExecuteQuery().DefaultView;
Related
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;
private void PopulateComboBox()
{
SqlConnection connection;
SqlCommand command;
SqlDataReader reader;
DataTable dt;
using (connection = new SqlConnection("connection string here"))
{
using (command = new SqlCommand("sql query here", connection))
{
connection.Open();
using (reader = command.ExecuteReader())
{
dt = new DataTable();
dt.Load(reader);
ComboxBox1.ValueMember = "col1";
ComboxBox1.DisplayMember = "col2";
ComboxBox1.DataSource = dt;
}
connection.Close();
}
}
}
That above code works fine. However, I want to add a static entry at index 0 of the ComboBox1 along with the dynamic entries above from the database. The static index 0 value should be "Select a value".
How do you combine static and dynamic data in a ComboBox?
You can insert an empty record into your DataTable before binding it to ComboBox:
dt = new DataTable();
dt.Load(reader);
DataRow row = dt.NewRow();
row["col1"] = "Something";
row["col2"] = "Something else";
dt.Rows.InsertAt(row, 0);
ComboxBox1.ValueMember = "col1";
ComboxBox1.DisplayMember = "col2";
ComboxBox1.DataSource = dt;
You can try:
comboBox1.Items.Add(new ListItem("Text", "Value"))
comboBox1.Items[0].Text = "Select a value";
and in your sql code:
.......
using (reader = command.ExecuteReader())
{
dt = new DataTable();
dt.Load(reader);
comboBox1.Items.Add("col1");
...
}
Use dt.Rows.InsertAt(Datarow row, int pos) to insert a new row at position 0 before binding the combobox.
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);
I tried to save a record from a query into a DataRow, but did not make it. I could need some help. This my code:
private DataSet CreateDataSet()
{
DataSet ds = new DataSet();
// create Countries table and columns
DataTable dtApplications = ds.Tables.Add("Applications");
DataColumn dtApplicationID = dtApplications.Columns.Add("ApplicationID", typeof(int));
DataColumn dtApplicationName= dtApplications.Columns.Add("ApplicationName", typeof(string));
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(MoahannedConnectionString);
SqlCommand cmd1 = new SqlCommand("select AppID,AppName from Application", con);
SqlDataAdapter da = new SqlDataAdapter();
SqlDataReader sdr = null;
dt.TableName = "Application";
con.Open();
sdr = cmd1.ExecuteReader();
while (sdr.Read())
{
AddDataToTable(dtApplicationID, dtApplicationName, dtApplications, ds);
}
}
private void AddDataToTable(DataColumn ID, DataColumn Name, DataTable myTable,DataSet ds)
{
DataRow row;
row = myTable.NewRow();
row["ApplicationID"] = ID;
row["ApplicationName"] = Name;
myTable.Rows.Add(row);
}
You can use the DataAdapter directly to load a DataTable:
using(var da = new SqlDataAdapter("select AppID,AppName from Application", con))
{
da.Fill(dt);
}
The rest of the code above is redundant in my opinion.
Side-note: You're getting the exception because you want to pass a field of a record to a DataRow's field. But actually you're passing the DataColumn.
This would work but is unnecessary:
row["ApplicationID"] = sdr.GetInt32(sdr.GetOrdinal("ApplicationID"));
row["ApplicationName"] = sdr.GetString(sdr.GetOrdinal("ApplicationName"));
Where sdr is your DataReader.