Duplicate column in DataTable when adding row - c#

I create a DataTable and bind it to a DataGrid. My DataSource consist of one Table (FooTable) which consist of one column (FooName).
The following codes runs fine - except that each time I add a new row, there is a duplicate Column fill in with the same data, which I don't know how to get rid of. See below image and code. I have only one FooName column and a duplicate column comes out.
/* Create a DataGrid dg1 */
DataGrid dg1 = new DataGrid();
DataGridTextColumn col = new DataGridTextColumn();
col = new DataGridTextColumn();
colA.Binding = new Binding("FooName");
colA.Header = "FooName";
dg1.Columns.Add(colA);
dataGrid1.Children.Add(dg1);
/* Create a DataTable and bind it to DataGrid */
SqlCeDataAdapter da = new SqlCeDataAdapter();
string sqlStr = #"SELECT * FROM FooTable";
da.SelectCommand = new SqlCeCommand(sqlStr, conn);
da.Fill(ds, "FooTable");
dt = ds.Tables["FooTable"];
DataRow newRow = dt.NewRow();
newRow["FooName"] = "Donkey";
dt.Rows.Add(newRow);
dg1.ItemsSource = ds.Tables[0].DefaultView;

try setting AutoGenerateColumns to false
dg1.AutoGenerateColumns = false

Try
dg1.AutoGenerateColumns = false;
Should do the work for you. For now the datagrid automatically generates the columns AND adds the one you asked

Related

DataGridView.DataSource not working when defining columns from code

I want to define the columns of my DataGridView manually from code. Something like this:
int index = 0;
string columnName = "something";
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.Name = columnName;
column.HeaderText = columnName;
myDataGridView.Columns.Insert(index++, column);
And then I bind the DataGridView.DataSource to a DataTable:
myDataGridView.DataSource = null;
table = new DataTable();
table = dbAccess.GetDataFromDB(); //This function returns a DataTable filled with data
myDataGridView.DataSource = table;
I already checked that after executing GetDataFromDB table is filled with data, but when binding it to DataSource, the DataGridView keeps all its row empty (although it creates as many rows as there are on the table).
Some code that I'm missing here?

c# show 2 columns of database with 28 columns

I have a database with 28 columns. First column is code, second Name and the rest are values.
public void displayData()
{
con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM gehaltes", con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.AutoResizeColumn(DataGridViewAutoSizeColumnsMode.DisplayedCells);
con.Close();
}
With this part of the program I see all the columns in the datagridview. I only want the first 2 but I have to use all the 28 columns if I want to make changes.
You can set the visible property of individual columns:
DataGridView dgv;
// ...
foreach(DataGridViewColumn c in dgv.Columns)
c.Visible = c.Name == "code" || c.Name == "Name";
Set the AutoGenerateColumns property of the DataGridView to false, and add two columns with the property DataPropertyName refering to the names that you want to display.
Example:
da.Fill(dt);
dataGridView1.AutoGenerateColumns = false;
DataGridViewColumn col = new DataGridViewColumn();
col.Name = "name";
col.HeaderText = "header";
col.DataPropertyName = "yourDBField";
dataGridView1.Columns.Add(col);
dataGridView1.DataSource = dt;
dataGridView1.AutoResizeColumn(DataGridViewAutoSizeColumnsMode.DisplayedCells);

How to perform multiplication on two column for datagrid view and assigning it in third column?

Here is my code, I am trying to display multiplication of Rate * Supply column values and assigning it to the Amount column in data grid view :
try
{
Query = "Select id,Code,Description,Rate,Cust_Id,Supply,Empty,Amount,Received from Items ";
adap = new SQLiteDataAdapter(Query, GlobalVars.conn);
ds = new DataSet();
adap.Fill(ds, "Items");
dtgVOuchers.DataSource = ds.Tables[0];
ds.Tables[0].Columns["Amount"].DefaultValue = (ds.Tables[0].Columns["Rate"].DefaultValue) * (ds.Tables[0].Columns["Supply"].DefaultValue); //error
//dtgVOuchers.Rows.Clear();
ds.Tables[0].Clear();
dtgVOuchers.Refresh();
}
Does anyone know how I can accomplish this functionality in data grid view ? . .Please help me to correct this code. Thanks
just use the query
Select id,Code,Description,Rate,Cust_Id,Supply,Empty,isnull(Rate,0)*isnull(Supply,0) as [Amount],Received from Items
DataTable myDataTable = new DataTable();
DataColumn quantityColumn = new DataColumn("Quantity");
DataColumn rateColumn = new DataColumn("Rate");
DataColumn priceColumn = new DataColumn ("Price");
quantityColumn.DataType = typeof(int);
rateColumn.DataType = typeof(int);
myDataTable.Columns.Add(quantityColumn);
myDataTable.Columns.Add(rateColumn);
myDataTable.Columns.Add(priceColumn);
//Set the Expression here
priceColumn.Expression = "Quantity * Rate";
foreach (DataGridViewRow row in dtgVOuchers.Rows)
{
row.Cells[dtgVOuchers.Columns["Amount"].Index].Value = (Convert.ToDouble(row.Cells[dtgVOuchers.Columns["Rate"].Index].Value) * Convert.ToDouble(row.Cells[dtgVOuchers.Columns["Supply"].Index].Value));
}
Use the below code..run a loop to update the Amount column in all rows
Note : Though this method is not preferred as it effects performance.So do this calculation in the sql query.I dont understand the reason behind not doing the munltiplication in SQL query..
foreach (DataRow row in ds.Tables[0].Rows)
{
row["Amount"]= Convert.ToDecimal(row["Rate"])* Convert.ToDecimal(row["Supply"]);
ds.Tables[0].AcceptChanges();
}
dtgVOuchers.DataSource = ds.Tables[0];
dtgVOuchers.Refresh();

How can I add extra column in datagridview when I fetch data from database

In my database I have 4 column. I fetch this database value in a datagridview. But I want to add two columns in datagridview. So, I want to make a datagridview with 6 columns. Within this 6 columns 4 columns will filled by database value. How can I do this?
OleDbConnection con = new OleDbConnection("CONNECTION STRING");
con.Open();
DataTable dtusers = new DataTable();
OleDbCommand cmd = new OleDbCommand("Select Code,Description,Qnty,Rate from PurchaseTable'", con);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dtusers);
dataGridView1.DataSource = dtusers;
dataGridView1.Columns[0].Name = "Code ";
dataGridView1.Columns[1].Name = "Description";
dataGridView1.Columns[2].Name = "Qnty";
dataGridView1.Columns[3].Name = "Rate";
con.Close();
Here are 4 columns. Code,Description,Qnty,Rate. I want to add two more columns in this datagridview. Amount and Narration. But Amount and Narration columns are not present in PurchaseTable.How can I do this?
If you want blank columns then create them and insert. If the data is in the database then add a join to your query to retrieve the data.
Adding blank columns
DataGridView dgv = new DataGridView();
dgv.DataSource = dtusers;
DataGridViewColumn amount = new DataGridViewColumn();
amount.HeaderText = "Amount";
amount.Name = "Amount";
dgv.Columns.Insert(0, amount);
DataGridViewColumn narration = new DataGridViewColumn();
narration.HeaderText = "Narration";
narration.Name = "Narration";
dgv.Columns.Insert(0, narration);
Assumed that you already have dtusers ..
Do Column adding to dtuser .. http://msdn.microsoft.com/en-us/library/hfx3s9wd.aspx
Do looping for all rows in your table to fill your new column
Assign the table as dgv datasource .. dataGridView1.DataSource = dtusers;
Because your column names are hardcoded, I think you can create a predefined columns in your datagridview through designer(Click datagridview -> choose Edit Columns).
Create all 6 columns you want. On the first four set DataPropertyName to name of the column from your query. Last two leave empty.
And remember set datagridview.AutoGeneratedColumns = false; before you binding data to datagridview...(somewhere in form_Load handler)
After this your code will be:
using (OleDbConnection con = new OleDbConnection("CONNECTION STRING"))
{
con.Open();
DataTable dtusers = new DataTable();
using(OleDbCommand cmd = new OleDbCommand("Select Code,Description,Qnty,Rate from PurchaseTable'", con))
{
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dtusers);
dataGridView1.DataSource = dtusers;
}
con.Close();
}

Adding a comboBox to a gridview in WinForms

I am trying to create a gridview with a string column, a checkbox column, and a dropdownlist/combobox column. The first two are finished (all code behind), just need help with the last one.
DataTable dt = new DataTable("tblAir");
dt.Columns.Add("Flight Details", typeof(string));
dt.Columns.Add("Prefered Seating", typeof(bool));
//doesn't work
dt.Columns.Add("Add Remark", typeof(ComboBox));
The data for the combobox is being supplied on load as we cannot work with a database.
Peter Bromberg has a detailed article on creating a Winforms gridview with comboboxes:
http://www.eggheadcafe.com/articles/20060202.asp
DataAccessLayer dal = new DataAccessLayer();
DataTable movies = dal.GetMovies();
gvMovies.DataSource = movies;
gvMovies.AllowUserToAddRows = false;
gvMovies.AllowUserToDeleteRows = false;
//Create the new combobox column and set it's DataSource to a DataTable
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.DataSource = dal.GetMovieTypes(); ;
col.ValueMember = "MovieTypeID";
col.DisplayMember = "MovieType";
col.DataPropertyName = "MovieTypeID";
//Add your new combobox column to the gridview
gvMovies.Columns.Add(col);

Categories