columns: Datagridview to Datatable - c#

I am facing this issue, I have datagridview and a datatable.
VPfn_CreateDataGrid();//This fuction creates gridview columns
DataTable invoice_table = (DataTable)invoice_data.DataSource;
now First thing, datagridview is empty when form loads. What I am trying to do is adding data to datagridview via multiple textboxes and combomoxes and for that I am using datatable.
private void btn_add_Click(object sender, EventArgs e)
{
DataRow x = invoice_table.NewRow();
x["serial_number"] = tsr.Text.ToString();
x["item"] = combo_items.SelectedItem.ToString();
x["item_rate"] = tr.Text;
x["item_qty"] = tq.Text;
x["item_unit"] = combo_unit.SelectedItem.ToString();
x["item_vat"] = combo_vat.SelectedItem.ToString();
x["amount"] = ta.Text;
invoice_table.Rows.Add(x);
invoice_data.Refresh();
}
And the error is "Column 'serial_number' does not belong to table"

first you have to create a the data table with the specific column. while your datagridview is empty the DataTable also will be empty.
DataTable invoice_table = (DataTable)invoice_data.DataSource;
infront of this..
while loading your form you can create datatable with the columns.
DataTable invoice_table; //Global
private void load()
{
invoice_table = new DataTable();
invoice_table.Columns.Add("serial_number", typeof(int));
invoice_table.Columns.Add("item");
.....
}
after that
private void btn_add_Click(object sender, EventArgs e)
{
DataRow x = invoice_table.NewRow();
x["serial_number"] = tsr.Text.ToString();
x["item"] = combo_items.SelectedItem.ToString();
x["item_rate"] = tr.Text;
x["item_qty"] = tq.Text;
x["item_unit"] = combo_unit.SelectedItem.ToString();
x["item_vat"] = combo_vat.SelectedItem.ToString();
x["amount"] = ta.Text;
invoice_table.Rows.Add(x);
invoice_data.Refresh();
}
Try this...

Related

Add row to existing Datatable

I want to add new row to existing datagridview. There is a problem beacause datagridview is connected to datasource and I can't add row by Rows.Add(). I have tried all commented lines and nothing works. Here is my code:
private void SaveButton_Click(object sender, EventArgs e)
{
if (start_tab == start_picker.ToString("dd-MM-yyyy HH:mm:00") & stop_tab != stop_picker.ToString("dd-MM-yyyy HH:mm:00"))
{
DateTime new_starttime = stop_picker;
DateTime new_stoptime = Convert.ToDateTime(stop_tab);
int new_cycletime = Convert.ToInt32(dataGridView3.Rows[dataGridView3.CurrentRow.Index].Cells["cycle_time"].Value) - Convert.ToInt32(textBox32.Text);
//devents.Rows.Add(new_starttime, new_stoptime, new_cycletime);
//DataTable devents = new DataTable();
//DataTable devents =
//DataRow newRow = devents.NewRow();
//newRow["start_time"] = new_starttime;
//newRow["stop_time"] = new_stoptime;
//newRow["cycle_time"] = new_cycletime;
//devents.Rows.Add(newRow);
dataGridView3.Rows.RemoveAt(dataGridView3.CurrentCell.RowIndex);
dataGridView3.Update();
dataGridView3.Refresh();
}
}
Data to datagridView is loaded from another private void:
private void Openbutton_Click(object sender, EventArgs e)
{
OpenReport();
EventClass eventData = new EventClass();
DataTable devents = eventData.Load_downtimes();
dataGridView3.DataSource = devents;
Adding to the DataTable should actually work.
The question is how you got devents here, it is declared locally in Openbutton_Click below.
You can best get it directly from the dgv (must be cast because DataSource can have various types)
var devents = (DataTable)dataGridView3.DataSource;
DataRow newRow = devents.NewRow();
newRow["start_time"] = new_starttime;
newRow["stop_time"] = new_stoptime;
newRow["cycle_time"] = new_cycletime;
devents.Rows.Add(newRow);

How to add values from dropdownlist and checkbox to gridview

EDIT: added a code and a image reference `public partial class DodavanjeNamirnice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dtTemp = new DataTable(); ;
dtTemp.Columns.Add(new DataColumn("Namirnica", typeof(string)));
dtTemp.Columns.Add(new DataColumn("Mjerna Jedinica", typeof(string)));
Session["Data"] = dtTemp;
}
}
protected void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["Data Source =.\\SQLEXPRESS; Initial Catalog = pra; Integrated Security = True"].ConnectionString;
string query = "SELECT * FROM Namirnica";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
var dataTableFromSession = Session["Data"] as DataTable;
var dataRow = dataTableFromSession.NewRow();
dataRow["Namirnica"] = DropDownList2.SelectedItem.Text;
dataRow["Mjerna Jedinica"] = CheckBoxList1.SelectedItem.Text;
dataTableFromSession.Rows.Add(dataRow);
Session["Data"] = dataTableFromSession;
GridView1.DataSource = dataTableFromSession;
GridView1.DataBind();
}
}`I got 2 dropdownlists , first one is filtering data in the 2nd,also 1st dropdownlist is connected to sql table as is the other one.
I have a checkbox which displays data from another table.
And my problem is: I want to add values I selected from 2nd dropdownlist and the checkboxlist to gridview in my webform.
I tried adding new columns manually but that ends up with displaying only first value from the dropdownlist, also displays only one value from the checkboxlist.
https://gyazo.com/59ea939b26deb55d3f31e68057249253
Set up a method to change the selected or created cell into a DataGridViewComboBoxCell and then feed it the datasource of your drop down list.
//could be whatever event you want such as the creation of a new DataRow in your DataGridView
private void gridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1[e.ColumnIndex, e.RowIndex] = new DataGridViewComboBoxCell();
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
cb.DataSource = dataSource;
}
You can do a similar thing for the checkbox but new DataGridViewCheckBoxCell() instead. After the user has selected a value you can just switch it back to being a regular cell if wanted.

Converting DataSource to DataTable returns null while filtering DataGridView

I'm totally new to Windows Forms and especially DataGridView control.
The problem is when I want to filter DataGridView by a specific column.
In the form load event I bind data to the DataSource of DataGridView like so :
private void Main_Load(object sender, EventArgs e) {
BindingSource bs = new BindingSource();
BindingList<Person> pList = new BindingList<Person> {
new Person {Id = 5, FName = "James", LName = "Allan", Age = 23, Country = "United States"},
// And so on ...
};
bs.DataSource = pList;
dataGridView1.DataSource = bs.DataSource;
}
Then here in click event of button1:
private void button1_Click(object sender, EventArgs e) {
DataTable dt = dataGridView1.DataSource as DataTable;
if (dt != null)
dt.DefaultView.RowFilter = $"FName LIKE '%{textBox1.Text}%'";
}
But the problem is that dt becomes null while dataGridView1.DataSource has value and number of records.
y = x as DataTable;
is not a conversion of your BindingList, but is (usually) equal to
if(x is DataTable)
y = (DataTable)x;
else
y = null;
You have to create a DataTable object by yourself, if you want to use its functionality.
A BindingList cannot be cast to a DataTable.
From How to make a DataTable from DataGridView without any Datasource? you may check this out.
private void button1_Click(object sender, EventArgs e) {
DataTable dt = new DataTable();
foreach(DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText);
}
foreach(DataGridViewRow row in dataGridView1.Rows)
{
DataRow newrow = dt.NewRow();
foreach(DataGridViewCell cell in row.Cells)
{
newrow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(newrow);
}
dt.DefaultView.RowFilter = $"FName LIKE '%{textBox1.Text}%'";
}

Add new empty row to dataGridView bound to DataSet

I am not handy at this. I have a dataGridView bound to SQL by a dataset. All column are generated by the dataset except one column which is replaced by a coded one which is a comboboxColumn.
To avoid new columns being generated while editing a row, I have set the allowUserToAddRows to false. Now I would like to add new empty rows by button click. I have tried in several way without any success.
Updated with full code
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.affitto_saTableAdapter.Fill(this.affitto_SADataSet.affitto_sa);
DataGridViewComboBoxColumn comboCol1 = new DataGridViewComboBoxColumn();
comboCol1.Name = "Periodo Rif.";
List<DateTime> periods = new List<DateTime>() { DateTime.Now.AddMonths(-2), DateTime.Now.AddMonths(-1), DateTime.Now, DateTime.Now.AddMonths(1), DateTime.Now.AddMonths(2) };
//Dates = Dates.OrderBy(x => x).ToList();
List<string> colSource = periods.Select(x => x.ToString("MMM/yyyy")).ToList();
comboCol1.DataSource = colSource;
dataGridView1.Columns.Add(comboCol1);
comboCol1.DataPropertyName = "Periodo";
dataGridView1.Columns["Periodo Rif."].DisplayIndex = 1;
}
private void button1_Click(object sender, EventArgs e)
{
/* DataTable dt = dataGridView1.DataSource as DataTable;
DataRow row = dt.NewRow();
dt.Rows.Add(row);*/
(dataGridView1.DataSource as DataTable).Rows.Add((dataGridView1.DataSource as DataTable).NewRow());
}
}
How can I add a new empty row to such DGV?
Here solution for your problem:
dataGridView1.Rows.AddCopy(myDataGridView1.Rows.Count - 1);
Since your DGV not binded with any of dataSource hence AddCopy of DataGridViewRow will add new row at end of DGV (at Rows.Count - 1).
private void button1_Click(object sender, EventArgs e)
{
this.dataGridView1.Rows.Add();
}

Datagrid Binding Question

I am new at this. I am trying to populate a datagrid from a table source. My code is attempting to do two things.
First it populates a dataGrid with columns from a table. Then it adds a column called "SELECT" at the end of the grid. This select is CheckBox. However, when I execute this code, it adds the "SELECT" column twice.
I want to see it once. What am I doing wrong?
private void BankFlow_Load(object sender, EventArgs e)
{
initMethod();
dataTable = getBankFlowData(globalConnection);
dataGridView1.DataSource = dataTable;
}
private static DataTable getBankFlowData(OracleConnection oc)
{
DataTable dt = new System.Data.DataTable();
try
{
OracleCommand od = oc.CreateCommand();
od.CommandText = "SELECT * FROM BANK_FLOW_SOURCE";
od.CommandType = System.Data.CommandType.Text;
OracleDataAdapter adapter = new OracleDataAdapter(od);
adapter.Fill(dt);
}
catch (Exception)
{
}
return dt;
}
private static void initMethod()
{
targetSystem = ConfigurationManager.ConnectionStrings["prototype"].ConnectionString.ToString();
Console.WriteLine("Target : {0}", targetSystem);
sourceSystem = ConfigurationManager.ConnectionStrings["qlprod8"].ConnectionString.ToString();
Console.WriteLine("Source : {0}", sourceSystem);
globalConnection.ConnectionString = sourceSystem;
globalConnection.Open();
}
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn();
col.HeaderText = "SELECT";
col.ReadOnly = false;
col.DefaultCellStyle.BackColor = Color.Beige;
dataGridView1.Columns.Add(col);
}
Your problem is that the databindingcomplete event happens more then you think. In fact anytime some data changes it will fire.
You need to add the column outside of the databindingcomplete event.
EDIT
Actually since you are databinding, you may want to consider adding the column to your datatable. You would do this before the binding the datatable to the grid. Essentially, just create a datacolumn named select, that has the type of boolean and then add the datacolumn to the datatable.

Categories