C# mysql view only specific columns in data grid view - c#

Short and probably easy question, I don't want to view in dataGridView columnID and few more columns as there is no use of viewing that info.
I have a clear code, the connection is open, the data loads fine and the comment code (btw most common solution in google) gives empty table with all columns (no rows).
I tried so many things that I can't even list them there :(
Any ideas?
DataTable SqlDataTable = new DataTable();
MySqlDataReader reader;
MySqlCommand sqlCommand = new MySqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "SELECT * FROM table_name";
reader = sqlCommand.ExecuteReader();
//while (reader.Read())
//{
// string columnID = reader["columnID"].ToString();
//}
SqlDataTable.Load(reader);
reader.Close();
sqlConnection.Close();
DataGridView = SqlDataTable;

First when U want view data in DataGridView U should set the data source of it's like
DataGridView.DataSource = yourDataTable
Second, if U want to hide DataGridView column, U most know the index of the column or the name and then you can use this code
I assume the first column is ID
So
By Index
DataGridView.Columns[0].Visible = false;
By Name
DataGridView.Columns["ID"].Visible = false;

Related

How to delete multiple rows in gridview then update data in database?

I want to delete some selected rows of data contained in grid view by pressing delete button, how to do it ?
This code works if data is not bound to the database:
foreach (DataGridViewRow row in DGV1.SelectedRows)
{
DGV1.Rows.RemoveAt(row.Index);
}
And this is my code to clear data in gridview based on value in Z_1_lblSupplier_Name.Text.
string sqlquery = "DELETE FROM tb_supplier_list WHERE Supplier_name='" + Z_1_lblSupplier_Name.Text + "'";
MySqlConnection mysqlconn = new MySqlConnection(mainconn);
MySqlCommand sqlcmd = new MySqlCommand(sqlquery, mysqlconn);
MySqlDataReader sdr;
mysqlconn.Open();
sdr = sqlcmd.ExecuteReader();
mysqlconn.Close();
I don't know how to combine them, I want users to be able to select multiple rows of data in grid view which they want to delete, then simultaneously data in database is also deleted.

C#: Fill DataGridView with DataTable creates empty table

I searched the web and Stack Overflow and found lots of descriptions on how to fill a DataGridView with the content of a DataTable. But still it does not work for me. My DataGridView shows the correct number of columns and rows, but they appear empty.
I use following method:
public void ShowDataInGrid(ref DataTable table)
{
BindingSource sBind = new BindingSource();
dbView.Columns.Clear();
dbView.AutoGenerateColumns = false;
sBind.DataSource = table;
dbView.DataSource = sBind; //Add table to DataGridView
dbView.Columns.Add("Date", "Date");
}
Before this I created a DataGridView of name "dbView" via the designer. I am not even sure, whether I need sBind. Without it I can bind the table directly to dbView, with the same bad result.
I suspect my table is the problem. It origins from a database (SQLite) and has several columns and rows (one of the columns has the name "Date"). It is definately filled with readable data.
I mainly read the table in using following commands (after this I manipulate the data in several different steps, like changing strings and adding numbers...):
string sql = "select * from Bank";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
table.Load(reader);
reader.Close();
table.AcceptChanges();
I think the problem might be, that the table entries are stored as objects and not as string, and hence can't be shown. That's why I tried to force the content to be strings with the following change to my table:
DataTable dbTableClone = new DataTable();
dbTableClone.Load(reader);
SQLiteDataReader reader.Close();
dbTableClone.AcceptChanges();
string[] dBHeader = new string[dbTableClone.Columns.Count];
dBHeader = ReadHeaderFromDataTable(dbTableClone); //own funktion, which reads the header
DataTable table;
table.Clear();
//will first create dbTable as empty clone, so I can set DataTyp of each Column
table = dbTableClone.Clone();
for (int col = 0; col > dBHeader.Length; col++) //first set all columns as string
{
dbTable.Columns[col].DataType = typeof(string);
}
foreach (DataRow Row in dbTableClone.Rows)
{
dbTable.ImportRow(Row);
}
This did not help me neither.
Another idea: I found some comments on similar problems, where it got apparently solved with quote: "I designed columns in the VS datagridview designer. Not the column name, but the column DataPropertyName must match with fields in database." Unfortunately I don't seem to be able to do/understand this.
Following you see one row of my input table.
Try fetching and setting to GridView this way
SqlLiteConnection con = new SqlLiteConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=DB.mdf;Integrated Security=True");
con.Open();
SqlLiteDataAdapter adap = new SqlLiteDataAdapter("select * from Bank", con);
DataSet ds = new System.Data.DataSet();
adap.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
Comment everything you've done so far, try this and let me know if this works for you or not. Change connection according to your DB.
I solved the problem.
The DataTable was fine. The problem was the setup of my DataGridView dbView. I set up dbView in the designer and somehow gave it a datasource. Now I set the datasource to "none" (In "DataGridView Tasks") and my data appears as intended.
Thanks to M Adeel Khalid for looking at my stuff. Him assuring to me that my code for the link was right, made me find the solution eventually.
At the end I really only needed to use a single line:
dbView.DataSource = table;

C# - How to Search and Filter in DataGridView without BindingSource

I wanna make a Search on Data Grid View in C# and SQLite, but I don't have Binding Source for Datagridview. I fill Datagridview with following code:
SQLiteConnection conn = new SQLiteConnection("Data Source=gasstation.sqlite;Version=3");
dt = new DataTable();
SQLiteCommand cmd = new SQLiteCommand("SELECT ID,fname, lname, nationalCode," +
personalCode, phone ,address, datetime(dateEnter) as dateEnter FROM Workers", conn);
conn.Open();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
SQLiteDataReader read = cmd.ExecuteReader();
DateTime date;
PersianCalendar pc = new PersianCalendar();
while (read.Read())
{
date = read.GetDateTime(7);
string datePC = string.Format("{0}/{1}/{2}", pc.GetYear(date),
pc.GetMonth(date), pc.GetDayOfMonth(date));
dgvUsers.Rows.Add(new object[] {
read.GetValue(0),
read.GetValue(1),
read.GetValue(2),
read.GetValue(3),
read.GetValue(4),
read.GetValue(5),
read.GetValue(6),
datePC });
}
read.Close();
conn.Close();
}
How to make a Search and filtering on Data Grid View with Text change event of Text Box.
I saw all of Question and Answer in StackOverflow but it doesn't right answer to my problem.
Your code is a little confused.
First you fill all the data into a DataTable with a DataAdapter, which looks fine. But then you read them once more in a DataReader and fill them into the DataGridView in code.
This is not necessary. Forget the reader and the loop it is in!
If the DataTable contains the data you can bind the DGV to that table:
dgvUsers.DataSource = dt;
When binding directly you can't sort or filter, though. Therefore it is better to create a BindingSource and make it the DGV's DataSource:
BindingSource bs = new BindingSource(dt, "");
Note the second parameter: It is empty, since we are using a single table as the data source of the BindingSource. Had we used a DataSet we would have put the TableName there. You don't have set the TableName property; it is better to do so, so let's change the instantiation to dt = new DataTable("someTableName");
Now we can bind the DGV to the data via the BindingSource:
dgvUsers.DataSource = bs;
Finally we can set the Sort and Filter properties as needed.
From some other control we can cast back to BindingSource, maybe like this:
private void textBox_lastName_TextChanged(object sender, EventArgs e)
{
BindingSource bs = dgvUsers.DataSource as BindingSource;
if (textBox_lastName.Text == "") bs.RemoveFilter();
else bs.Filter = "lname like '%" + textBox_lastName.Text + "%'";
}
I note that in the loop you are creating a formatted date field. I suspect that it is the reason for creating that loop in the first place..? But you can add it to the DataTable just as well; the best way, of course is, as always, to select the value you want and let the DBMS do all the work.
But if you want to do very special stuff you don't trust the SQL function to achieve, like using that PersianCalendar class, you can add a dummy field to your SELECT:
SQLiteCommand cmd = new SQLiteCommand("SELECT ID,fname, lname ,nationalCode, " +
"personalCode, phone, address, datetime(dateEnter) as dateEnter " +
"\"\" as pcDate FROM Workers", conn);
..and after filling the table fill that dummy field with the special values:
DateTime date;
PersianCalendar pc = new PersianCalendar();
foreach(DataRow row in dt.Rows)
{
date = row.Field<DateTime>("dateEnter");
string datePC = string.Format("{0}/{1}/{2}",
pc.GetYear(date), pc.GetMonth(date), pc.GetDayOfMonth(date));
row.SetField<string>("pcDate", datePC);
}
Of couse you may now want to hide the dateEnter column from the DVG:
dgvUsers.Columns["dateEnter"].Visible = false;

Alternative Ways In Adding New Rows in Datasource Data Grid View

I'm creating a project in C# windows form. What I'm trying to do is add new rows in the datasource data grid view. But the problem is, the error says that adding new rows can't add programmatically in the datasource data grid.
Here's my method in fetching the data and transfer it in the data grid view.
public DataTable GetData(ClassName classVar){
SqlCommand cmd = new SqlCommand();
cmd.Connection = ...; // My connection string
cmd.CommandType = CommandType.Text;
cmd.CommandText = ...; // My Query
DataTable table = new DataTable();
table = ...ExeReader(cmd);
return table;
}
The Codes inside my form
DataTable getDataTable;
getDataTable = ClassQuery.GetData(classVar);
dgv_details.DataSource = getDataTable;
And this is my add button
dgv_details.Rows.Add(txtBox1.Text,txtBox2.Text);
What are the alternative ways in adding data inside the datasourced datagridview?
Thanks in advance.
Try the below code. First add row to datatable and then bind that table to datagridview.
DataRow dr = datatable1.NewRow();
dr[0] = "HAI"; // add data in first column of row
datatable1.Rows.InsertAt(dr, 0); // insert new row at position zero
datatable1.Rows.Add(dr); // addnew row at last

C#: DataGridView shows only one row

I have a problem with a datagridview in C#. I get the data via query from a mysql-database. But for some reason, only the first row from the result is displayed in the gridview. I use the following code to do this stuff:
MySqlCommand command = new MySqlCommand(query, Globals.Connection);
reader = command.ExecuteReader();
while (reader.Read())
{
object[] dataset = new object[7];
dataset[0] = reader["sto_name"];
dataset[1] = reader["esss"];
dataset[2] = reader["onl_name"];
dataset[3] = reader["rpc_id"];
if (reader["datum_aufstellung"].ToString() != "0")
{
dataset[4] = getDate(reader["datum_aufstellung"]);
}
else
{
dataset[4] = "Kein Datum gesetzt";
}
if (reader["datum_abbau"].ToString() != "0")
{
dataset[5] = getDate(reader["datum_abbau"]);
}
else
{
dataset[5] = "Kein Datum gesetzt";
}
dataset[6] = reader["id"];
dataGridView1.Rows.Add(dataset);
}
It worked, a few lines of code earlier. ^^
Do you have an idea, what the problem is?
UPDATE:
The content of the while loop is executed only one time. I was also wondering about that fact, before I asked my question here. But if I execute the Query in an MySQL-Client, it returns more rows than one.
UPDATE 2:
I've noticed, that while the whole content of the while-loop is commented, the loop is executed exactly the same times as there are rows in the query-result. Any ideas?
UPDATE 3:
It seems that everything after
dataGridView1.Rows.Add(dataset);
is not executed. Not only in the loop, but in the whole function.
But why?
PROBLEM SOLVED:
There was nothing wrong with the code posted here. I had an event in the rest of the code, which executed something, when a row in the dgv is entered. I suppose the loop breaked, when that happened. After removing that event, the dgv was properly filled.
You should use a DataAdapter and use it to populate a DataTable. Create a method for grabbing the data like this :-
public DataTable GetDataTable()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection (#"YourCOnnectionString"))
{
using (SqlCommand cmd = new SqlCommand (query, con))
{
var adaptor = new SqlDataAdapter ();
adaptor.SelectCommand = cmd;
con.Open();
adaptor.Fill(dt);
return dt;
}
}
}
Then You can reference it with your DataGrid :-
DataTable Result = GetDataTable();
DatagridView1.DataSource = Result;
Check the RowCount property on the Grid. It maybe set to 1 if so increase it to the desired amount of rows.
There is another easy way.
You can use DataTable instead of dataset and set the dataGridView's DataSource to that DataTable.
It will solve your problem and also using that you can set the column Headers easily.

Categories