I've create a datagridview that show me my data. Then I should click on a row and I'd like to show a form where I can update my values.
Is it possible go to the previous/next element of the datagridview in another form? Because I'd like to create two buttons that allow me to scan the whole table and update each value.
Can you help me, please? I really don't know where to start
EDIT: This is the code to show my data
public static string StringaConnessione = "Data Source=localhost;Database=db;userid=root;password='';";
public static MySqlConnection Connessione = new MySqlConnection(StringaConnessione);
void MostraBtnClick(object sender, EventArgs e)
{
Connessione.Open();
MySqlDataAdapter SDA=new MySqlDataAdapter("SELECT * FROM Acquisti",Connessione);
DataTable DATA= new DataTable();
SDA.Fill(DATA);
dataGridView1.DataSource=DATA;
Connessione.Close();
Related
Using C# and Winform.
I read a couple of similar questions but couldn't find any great answers that could interlock with my code. So, bear with me and thank you in advance for helping me.
I have a single form that contains multiple User Controls. Inside the first user control, you can insert, update and delete records from the database. In the second User Control, there is a datagridview that is populated with all records.
The problem I have is that whenever I insert, update or delete a record inside the first user control. It won't refresh inside the datagridview when I swap to the second user control.
Beneath is the second user control that populates the datagridview
private void populate()
{
database.OpenConnection();
string query = "SELECT id, name, qoute, time, date from maintable";
SQLiteDataAdapter sda = new SQLiteDataAdapter(query, database.connection);
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(sda);
var ds = new DataSet();
sda.Fill(ds);
dtgNav.DataSource = ds.Tables[0];
databas.CloseConnection();
}
private void Navigation_Load(object sender, EventArgs e)
{
populate();
dtgNav.Columns[0].HeaderText = "ID";
}
public void Refresh()
{
this.Refresh();
}
Beneath is the code for adding a record to the datagridview in the first user control
private void btnAdd_Click(object sender, EventArgs e)
{
database.OpenConnection();
string query = "INSERT INTO maintable (`id`, `name`, `qoute`, `time`,`date`) VALUES (#Id, #Name, #Qoute, #Time, #Date)";
SQLiteCommand command = new SQLiteCommand(query, database.connection);
command.Parameters.AddWithValue("#Id", tbxID.Text);
command.Parameters.AddWithValue("#Name", tbxName.Text.Trim());
command.Parameters.AddWithValue("#Qoute", tbxQoute.Text.Trim());
command.Parameters.AddWithValue("#Time", tbxTime.Text.Trim());
command.Parameters.AddWithValue("#Date", dtpDate.Value.ToString("yyyy-MM-dd"));
command.ExecuteNonQuery();
MessageBox.Show("Added new event into the database.");
database.CloseConnection();
usercontrol2.Refresh();
}
I would appreciate it if we found a way to refresh the datagridview when the button is clicked without changing the original code all too much.
You have a public void Refresh method in the second usercontrol, try modifying this.Refresh();, to say populate();. this should call your private void populate method that you called when loading which should reload the grid. Let me know if this helps.
I am quite new to C# and I am trying to populate fill several textboxes with data from a selected combobox.
I have my main window with the textboxes and comboboxes and a separate class for the connection to the database (I am using XAMPP/PhpMyAdmin).
I managed to fill the comboboxes with the data from the database, but I cannot fill the texboxes from the selected combobox.
I checked other questions and tutorials, but all I managed to achieve is to get the primary key into the text box, but I need different columns from the table, depending on the textbox.
I populated the combobox from the database:
void Completez_Combo_Furnizor()
{
combo_furnizor = DB_Furnizori.Combo_Furnizor();
comboBoxFurnizor.Items.Clear();
comboBoxFurnizor.DataSource = combo_furnizor;
comboBoxFurnizor.ValueMember = "id_furnizor";
comboBoxFurnizor.DisplayMember = "nume";
}
I double clicked on the combobox and wrote the following, but all I can get is the primary key (the first column). In the textbox, I need to get the 7th column (which is a double type.
private void comboBoxFurnizor_SelectedIndexChanged(object sender, EventArgs e)
{
textBoxPret.Text = comboBoxFurnizor.SelectedItem.ToString();
}
And this is from the database class (DB_Furnizori.cs), where I open the connection and have multiple queries for the database.
public static DataTable Combo_Furnizor()
{
conn.Open();
MySqlCommand comboFurnizor = new MySqlCommand("SELECT * from furnizori ORDER BY nume", conn);
MySqlDataAdapter adaptc = new MySqlDataAdapter(comboFurnizor);
DataTable combo_furnizori = new DataTable();
adaptc.Fill(combo_furnizori);
conn.Close();
return combo_furnizori;
}
Please help.
For your SelectedIndexChanged Method :
private void comboBoxFurnizor_SelectedIndexChanged(object sender, EventArgs e)
{
textBoxPret.Text = comboBoxFurnizor.SelectedItem.ToString();
}
You need to make another call to the database and retrieve the data you want using the values/Id (or whatever is the unique identifier) from the combobox. If you're trying to retrieve data on a selected index change you need to reference some type of data source for me I used a DataSet instead of DataTable (makes retrieving values in cells easier):
string StoredProc = "GetItemNotes";
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(StoredProc, conn);
SqlDataAdapter da = new SqlDataAdapter();
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(ds);
For populating the data within my Textbox I did this:
Notes.Text = ds.Tables[0].Rows[0]["Notes"].ToString();
So I'm trying to cope with an app project in c#/mssql.
It is Windows Froms app.
I'm connected to db, I can show all the tables in my db in the form onload, but i don't know how, or if I can do sth like: when these table names shows click on any and it will send the db name as a variable to function, which will show me the content of the folowing table. I've learned about cellclick event, but i still don't know how do i make it work.
So the code below works perfectly fine
DbClassShow showObj = new DbClassShow();
private void MyWindow_Load(object sender, EventArgs e)
{
DataTable dt = showObj.Select();
QueryView.DataSource = dt;
}
but I want it to show the content of the table, when i click on it, but I can't attach like clik event to table name, because when the app is not running i can't even see content of the data grid view.
What do I do in this situation?
Sorry guys for bothering, I've been trying this and had no clue, but finally I resolved it on my own! Here's what i did:
dbClassTables showTab = new dbClassTables();
private void QueryView_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
int indexOfRow = e.RowIndex;
DataGridViewRow selectedRow = QueryView.Rows[indexOfRow];
DataTable dt1 = showTab.Select(selectedRow.Cells[2].Value.ToString());
QueryView.DataSource = dt1;
}
Created a new class with select method with parameter and it works, I'm gonna make it more valid using abstract class or interface i think, but yeah, that's it.
public DataTable Select(string tbl_name)
{
...
string sql = "SELECT * FROM {0}";
string data = tbl_name;
sql= string.Format(sql, data);
When user select any record from the GridView then my DetailView is updated based on the selection of the GridView. So what I am trying to do is that when I delete anything from the DetailView then I want to refresh the GridView so basically I don’t want to show still the deleted record in the GridView. I have tried to resolve this issue by doing the data bind after my connection and SQL statement but it does not refresh it. One thing to note is that I am using a Accordion pane but both my gridview and the detailview are on the same pane. I am not sure if this is breaking anything. Here is my code:
protected void Refresh_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName.Equals("Delete", StringComparison.CurrentCultureIgnoreCase))
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("select ID, Name, Address from dbo.MyTable", con);
DataTable dt = new DataTable();
da.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
}
You may use the event of the Data view called "ItemDeleted" as follows:
DetailViewName_ItemDeleted(object sender,
DetailsViewDeletedEventArgs e)
{
// Refresh the GridView control after a new record is updated
// in the DetailsView control.
GridViewName.DataBind();
}
The above code is from the official MSDN site for detail view control.
The other way (which I prefer) is to handle the data grid during the Page_load procedure so when you press your delete button in the detail view, the page will perform a postback.
So in the procedure Page_load you can call another procedure which fills the data grid. The code might be like this:
if (isPostback)
{
FillGrid();
}
private void FillGrid()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("select ID, Name, Address from dbo.MyTable", con);
DataTable dt = new DataTable();
da.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
Your code doesn't show anything where the record is actually deleted so it's understandable that when you re-fetch the data still contains everything.
What you need to do is:
Execute a sql statement to delete the record
Re-fetch the data
Rebind the data.
If you follow those 3 steps it will work.
try to use the event that is called in case of pressing the delete key from the DGV
private void DGV_DeleteKeyPressed(object sender, KeyEventArgs e)
{
//enter code here
}
I want to show a master / detail relationship using two datagridviews and DataRelation in C#.
The relation between the master and the detail table is an ID from type string (and there is no chance to change the ID to type integer).
It seems like the DataGridView is not able to update the detail view when changing the row in the master table.
Does anybody know if it is possible to achieve a master / detail view using a string ID and if yes, how? Or do I have to use an external DataGrid from another company?
Personally I don't see a difference in using a string instead of an integer. The only thing I can think of is that the grid cannot handle a master detail view using a string ID relation.
UPDATE: The issue is solved, the problem was that one relation was from type nchar and had blancs at the end of the string. Thanks for the help!
Here is an example, please create a new VS 2008 project and copy the code. Change the connection string and the datarelation:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
public class Form1 : System.Windows.Forms.Form
{
private DataGridView masterDataGridView = new DataGridView();
private BindingSource masterBindingSource = new BindingSource();
private DataGridView detailsDataGridView = new DataGridView();
private BindingSource detailsBindingSource = new BindingSource();
[STAThreadAttribute()]
public static void Main()
{
Application.Run(new Form1());
}
// Initializes the form.
public Form1()
{
masterDataGridView.Dock = DockStyle.Fill;
detailsDataGridView.Dock = DockStyle.Fill;
SplitContainer splitContainer1 = new SplitContainer();
splitContainer1.Dock = DockStyle.Fill;
splitContainer1.Orientation = Orientation.Horizontal;
splitContainer1.Panel1.Controls.Add(masterDataGridView);
splitContainer1.Panel2.Controls.Add(detailsDataGridView);
this.Controls.Add(splitContainer1);
this.Load += new System.EventHandler(Form1_Load);
this.Text = "DataGridView master/detail demo";
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Bind the DataGridView controls to the BindingSource
// components and load the data from the database.
masterDataGridView.DataSource = masterBindingSource;
detailsDataGridView.DataSource = detailsBindingSource;
GetData();
// Resize the master DataGridView columns to fit the newly loaded data.
masterDataGridView.AutoResizeColumns();
// Configure the details DataGridView so that its columns automatically
// adjust their widths when the data changes.
detailsDataGridView.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
}
private void GetData()
{
try
{
// Specify a connection string. Replace the given value with a
// valid connection string for a Northwind SQL Server sample
// database accessible to your system.
String connectionString =
"";
SqlConnection connection = new SqlConnection(connectionString);
// Create a DataSet.
DataSet data = new DataSet();
data.Locale = System.Globalization.CultureInfo.InvariantCulture;
// Add data from the Customers table to the DataSet.
SqlDataAdapter masterDataAdapter = new
SqlDataAdapter("select * from customers", connection);
masterDataAdapter.Fill(data, "Customers");
// Add data from the Orders table to the DataSet.
SqlDataAdapter detailsDataAdapter = new
SqlDataAdapter("select * from orders", connection);
detailsDataAdapter.Fill(data, "Orders");
// Establish a relationship between the two tables.
DataRelation relation = new DataRelation("CustomersOrders",
data.Tables["Customers"].Columns["strID"],
data.Tables["Orders"].Columns["strID"]);
data.Relations.Add(relation);
// Bind the master data connector to the Customers table.
masterBindingSource.DataSource = data;
masterBindingSource.DataMember = "Customers";
// Bind the details data connector to the master data connector,
// using the DataRelation name to filter the information in the
// details table based on the current row in the master table.
detailsBindingSource.DataSource = masterBindingSource;
detailsBindingSource.DataMember = "CustomersOrders";
}
catch (SqlException)
{
MessageBox.Show("To run this example, replace the value of the " +
"connectionString variable with a connection string that is " +
"valid for your system.");
}
}
}
I looked through your code and it looks basically OK. Please try to trim it a little further though.
But I find the Field Names "strId" a bit suspicious, is that really what the columns are called in the Database?
Tip: Put a break on the Relations.Add(relation) line and inspect the relation object carefully.
The code doesn't show where/how the bindinsource components are made, maybe they have some designtime properties set (Filter).