I am a newbie in C# so I don't know if I will address my problem correctly so please bear with me. I have 3 DataGridViews (datagridview1, datagridview2, datagridview3). All are located in the same window but they are in a different tab (I have a tab control).
The purpose of each DataGridView is to display data for three tables from database. So every time I click a button, it retrieves data. But here is my problem, when datagridview1 displays the data after clicking the button, then I go to the next tab and click again the retrieve button, the datagridview2 shows the data that was displayed to datagridview1. Same thing to datagridview3.
I'm using DataTable as the data source for those DataGridViews. And somewhere in my script the query will change so I think there's no problem with the query. What I found is that the DataTable does not clear it's data even when the query already changed.
I'm using WinForms, please help me. Thanks.
Here is the code I used in binding the datagridview to a datasource:
currentdatagrid.DataSource = execute.InitConn2(query, CompleteTablename);
Note: "execute.InitConn2(query, CompleteTablename)" will return a datatable.
Try doing something like the following example and see if it works for you. The static method GetData returns a new data table each time. You need to update the SqlConnection with your own connection string.
public static void Main(string[] args)
{
DataGrid dg1 = new DataGrid();
DataGrid dg2 = new DataGrid();
DataGrid dg3 = new DataGrid();
dg1.DataSource = GetData("select * from table1");
dg1.DataBind();
dg2.DataSource = GetData("select * from table2");
dg2.DataBind();
dg3.DataSource = GetData("select * from table3");
dg3.DataBind();
}
public static DataTable GetData(string sqlQuery) {
try
{
DataTable dt = new DataTable();
// set your connection here
SqlConnection conn = new SqlConnection("");
// execute query with your connection
SqlDataAdapter adapt = new SqlDataAdapter(sqlQuery, conn);
// open connection, fill data and close
conn.Open();
adapt.Fill(dt);
conn.Close();
return dt;
}
catch (Exception ex) {
throw ex;
}
}
To use a dataset use the following:
public static void Main(string[] args)
{
DataGrid dg1 = new DataGrid();
DataGrid dg2 = new DataGrid();
DataGrid dg3 = new DataGrid();
DataSet ds = GetData(#"select * from table1;
select * from table2;
select * from table3");
dg1.DataSource = ds.Tables[0];
dg1.DataBind();
dg2.DataSource = ds.Tables[1];
dg2.DataBind();
dg3.DataSource = ds.Tables[2];
dg3.DataBind();
}
public static DataSet GetData(string sqlQuery) {
try
{
DataSet ds = new DataSet();
// set your connection here
SqlConnection conn = new SqlConnection("");
// execute query with your connection
SqlDataAdapter adapt = new SqlDataAdapter(sqlQuery, conn);
// open connection, fill data and close
conn.Open();
adapt.Fill(ds);
conn.Close();
return ds;
}
catch (Exception ex) {
throw ex;
}
}
Related
I have a query that loads data from a MySQL db into a datagridview but in that same datagridview I have a combobox. The items list is being populated from another query. When the user first saves the data, he selects an item from the combobox and fills in the other columns by hand. The row is then saved with an insert query. What I want to do is display what was previously saved in the datagridview including the combobox choice. How do I go about showing the list item that was previously saved as the default item in the combobox?
here is the save code:
public void SaveOperations()
{
// create new row in project_operations with datagridview operations
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
MySqlConnection con = new MySqlConnection(conSettings.ToString());
MySqlCommand cmd = new MySqlCommand(#"insert into shopmanager.project_operations (products_product_id, operation_name, operation_description) values (#products_product_id, #operation_name, #operation_description)", con);
con.Open();
foreach (DataGridViewRow row in operation_dataGridView.Rows)
{
try
{
if (row.IsNewRow) continue;
cmd.Parameters.AddWithValue("#products_product_id", product_id.Text);
cmd.Parameters.AddWithValue("#operation_name", row.Cells["combo"].Value);
cmd.Parameters.AddWithValue("#operation_description", row.Cells["Description"].Value);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
MessageBox.Show("Operation Sauvegardé");
con.Close();
}
Here is the load code. This loads the data to the other cells in the row apart from the combobox. When I try to load the operation_name, it's creates a new column but what I want is for the operation name to be in the combobox. How can I achieve that?
private void LoadData()
{
// fill textbox columns
MessageBox.Show("load operations data textboxes");
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["shopmanagerConnectionString1"];
MySqlConnection con = new MySqlConnection(conSettings.ToString());
DataTable dt = new DataTable();
DataSet ds = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand cmd;
cmd = new MySqlCommand(#"select operation_description as 'Description', operation_start_date as 'Début', operation_finish_date as 'Fin', users_employee_number as 'Employé' from shopmanager.project_operations where products_product_id = #product_id", con);
try
{
con.Open();
cmd.Parameters.AddWithValue("#product_id", product_id.Text);
cmd.ExecuteNonQuery();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
dt = ds.Tables[0];
operation_dataGridView.DataSource = dt;
cmd.Parameters.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
con.Close();
}
I think after setting the dataSource, I'll do like below (for both combo or check):
//ADD COLUMNS
var comboBox = new DataGridViewComboBoxColumn();
comboBox.HeaderText = "Header title";
comboBox.Name = "combo box";
var dataRow = new ArrayList();
foreach(var dr in dt.Rows)
dataRow.Add(dr["fieldName"].ToString()); // this will be the combo box data from database
// add data to combobox
comboBox.Items.AddRange(dataRow.ToArray());
// finally add the combo box to dgv
dataGridView1.Columns.Add(comboBox);
}
I have this form,when I give it some ID and click the highlighted button,shows me some info in a datagridview taken from a database.
First Form
The code of the button is here:
private void kerkoButton_Click(object sender, EventArgs e)
{
try
{
Konektimi();
string query = "SELECT * FROM Vizita WHERE PacientiId=#pacientiId";
using (SqlCommand command = new SqlCommand(query, conn))
{
command.Parameters.AddWithValue("#pacientiId",pacientiTextBox.Text);
conn.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
DataTable dt = new DataTable();
dt.Load(reader);
forma.vizitaDataGridView.DataSource = dt;
forma.ShowDialog();
}
else
{
MessageBox.Show("Nuk ka të dhëna për këtë pacient");
}
}
conn.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Suposing that we get something from the database we get this:
Second Form,with the results
This is a new form that will be opened after clicking the kerkoButton.
NOW,the problem is this: When I edit a row(or some rows),if I click Save,the changes will not be saved in the database.
What should i do?
Could I make a SaveButton in this datagridform?If yes,how?
Take a look at "how to update row in DataGridView?"
You can access the edited row by using the property CurrentRow of your DataGridView like so:
DataRowView dataRowView = yourDataGridView.CurrentRow.DataBoundItem as DataRowView;
DataRow[] rowsToUpdate = new DataRow[] { dataRowView.Row };
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Vizita", con);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.Update(rowsToUpdate);
Alternatively, if you want to update all edited rows at once, you have to create a flag and set it to true whenever you change a property using the PropertyChanged event.
When clicking "Save" you iterate through all rows and add the edited ones to rowsToUpdate.
private void fill()
{
adptr = new OleDbDataAdapter(#"SELECT * FROM LibraryInfo WHERE First_Name='"+LoginName+"'", cn);
//LoginName is a string variable for displaying users info after the login
ds.Clear();
adptr.Fill(ds);
dataGridView1.DataSource = "";
dataGridView1.DataSource = ds.Tables[0];
}
After the database updated, GridView didn't show data.
Taken from this msdn article on the DataBind Property.
ASP EXAMPLE
void Page_Load(Object sender, EventArgs e)
{
// This example uses Microsoft SQL Server and connects
// to the Northwind sample database. The data source needs
// to be bound to the GridView control only when the
// page is first loaded. Thereafter, the values are
// stored in view state.
if(!IsPostBack)
{
// Declare the query string.
String queryString =
"Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]";
// Run the query and bind the resulting DataSet
// to the GridView control.
DataSet ds = GetData(queryString);
if (ds.Tables.Count > 0)
{
AuthorsGridView.DataSource = ds;
AuthorsGridView.DataBind();
}
else
{
Message.Text = "Unable to connect to the database.";
}
}
}
DataSet GetData(String queryString)
{
// Retrieve the connection string stored in the Web.config file.
String connectionString = ConfigurationManager.ConnectionStrings["NorthWindConnectionString"].ConnectionString;
DataSet ds = new DataSet();
try
{
// Connect to the database and run the query.
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
// Fill the DataSet.
adapter.Fill(ds);
}
catch(Exception ex)
{
// The connection failed. Display an error message.
Message.Text = "Unable to connect to the database.";
}
return ds;
}
This snippet shows you how to (a) bind your dataset to a gridview, by assigning it using the Databind method.
The site also says:
Use the DataBind() method to bind data from a data source to the GridView control. This method resolves all data-binding expressions in the active template of the control.
SOLUTION
I would like to reference the line saying:
AuthorsGridView.DataBind();
which actually binds the data to the control.
SIDE NOTE
To protect yourself from SQLi, you should read up on SQL Parameters, and not direct concatenation.
WINFORM EXAMPLE
Tutorial was found: here
//create the connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\myDatabase.mdb";
//create the database query
string query = "SELECT * FROM MyTable";
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
Also:
//the DataGridView
DataGridView dgView = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dgView.DataSource = bSource;
Use are missing to call databind method here.Use following code :
DataAdapter adapter=new DataAdapter(SqlCommand,SqlConn);
DataTable tbl=new Datatable();
adapter.Fill(tbl);
GridView1.DataSource=tbl;
GridView1.DataBind();//This line is missing in your code
try with this format?
Hi I have a ASPX Bulletted list control
<asp:BulletedList id="blProductsBulletedList"
BulletStyle="Disc"
DataTextField="CheckListsFriendlyName"
runat="server">
</asp:BulletedList>
and i have a single column datatable bound to it in the page load:
string strSQLQuery = "SELECT [CheckListsFriendlyName] FROM [SingleEnded2].[dbo].[WOCFriendlyNames]";
// Run the query and bind the resulting DataSet
// to the GridView control.
DataTable dt = getCheckListExampleList(strSQLQuery);
if (dt.Rows.Count > 0)
{
blProductsBulletedList.DataSource = dt;
blProductsBulletedList.DataBind();
}
}
further down in the cs file is the 'getCheckListExampleList()':
DataTable getCheckListExampleList(string strSQLQuery)
{
SqlConnection seConnection = new SqlConnection(Databases.getDbConnectionString("csSingleEnded2"));
DataTable dt = new DataTable();
SqlCommand seCmd = new SqlCommand(strSQLQuery, seConnection);
try
{
SqlDataAdapter sda = new SqlDataAdapter();
seCmd.Connection = seConnection;
sda.SelectCommand = seCmd;
sda.Fill(dt);
}
catch (Exception ex){
// The connection failed. Display an error message.
throw new Exception("Unable to connect to the database", ex);
}
return dt;
}
This works, however the list does not appear bulleted and just appears as if its just a view of the records. Can anyone point me in the right direction to show each result as a bulleted list item and also after X amount of results add titles to split the results up into sections?
I have a WPF Browserapplication which gets data stored on a SQL Server, stores it in a DataTable and displays it in a DataGrid. Now I want to have a TextBox where you can search entries in the DataTable but when I load the Application I'm getting an error telling me, that the row [Company] cannot be found.
I think the problem is, that the DataTable isn't yet filled when the filter is being applied to the DataTable. Can someone please give me a hint how to make this working?
DataTable dt = new DataTable();
public Page1()
{
InitializeComponent();
showSQLData();
}
private void showSQLData()
{
string sqlConnectionString = #"blabla";
string sqlCommandString = "SELECT * FROM Excel_import";
using (SqlConnection sqlConnection = new SqlConnection(sqlConnectionString))
{
SqlCommand cmd = new SqlCommand(sqlCommandString, sqlConnection);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
dataGridSQLData.ItemsSource = dt.DefaultView;
}
}
private void textBoxSearch_TextChanged(object sender, TextChangedEventArgs e)
{
dt.DefaultView.RowFilter = string.Format("Company LIKE '%{0}%'", textBoxSearch.Text);
}
Based on you latest comment I would guess that textBoxSearch_TextChanged is being fired from within the InitializeComponent() call. You could check that dt.Rows.Count > 0 in textBoxSearch_TextChanged and return if that condition is not met.