insert item in combobox after binding it from a Dataset in c# - c#

I have to insert "Select" at top after combobox is bound from dataset.i tried this but it isn't working.Throws error "dataset doesn't have any definition for cast".I think i am not using it properly.Commented code is the part i tried but not working.
cmbCategory.DataSource = dsCat.Tables[0];
cmbCategory.DisplayMember = "CategoryName";
cmbCategory.ValueMember = "ID";
// cmbCategory.Items.Add("Select");
// cmbCategory.SelectedText = "Select";
// cmbCategory.DataSource =(new object[] { "Select" }).Concat(this.liveReportingDalc.GetCategoriesByType(CategoryType.RegistrationType).Cast<object>());

You have to Insert to the object you are databinding to rather than to the combobox. You can't insert directly into the combobox.
You can use this:
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("CategoryName");
DataRow dr = dt.NewRow();
dr["CategoryName"] = "Select";
dr["ID"] = 0;
dt.Rows.InsertAt(dr, 0);
cmbCategory.DisplayMember = "CategoryName";
cmbCategory.ValueMember = "ID";
cmbCategory.DataSource = dt;
cmbCategory.SelectedIndex = 0;
This is very straight forward example.

You cannot add items to a ComboBox after binding it to a data source. To add or remove items from a ComboBox with a bound data source, you have to do it through data source itself.
You can insert a DataRow into your table and it will be automatically added to your ComboBox. Try the following:
DataRow dr = dsCat.Tables[0].NewRow();
dr["CategoryName"] = "Select";
dr["ID"] = 123;// Some ID
dsCat.Tables[0].Rows.Add(dr);

// cmbCategory.DataSource =(new object[] { "Select" }).Concat(this.liveReportingDalc.GetCategoriesByType(CategoryType.RegistrationType).Cast<object>());
You might be able to do this, but your syntax is wrong somehow.
Maybe you can split it up until you figure it out and then compress it back into in-line functions.
List <object> catData = new List <object> { "Select" };
DataSet catByType = this.liveReportingDalc.GetCategoriesByType(CategoryType.RegistrationType);
foreach(DataRow oRow in catByType.Tables[0].Rows)
{ catData.Add(oRow.ItemArray[0]); }
But for this to work you need to consolidate your understanding of the data coming back from the GetCategoriesByType function. Will the objects be text like "Select"?.

You can use dsCat.Rows.Add method.
dsCat.Rows.Add(0, "Other"); // this will add row
cmbCategory.DataSource = dsCat.Tables[0];
cmbCategory.DisplayMember = "CategoryName";
cmbCategory.ValueMember = "ID";

Related

How do i add more cells to a column of datagridview?

Now i have one cell i added it in the designer but if i want to add more cells in my code ?
I tried in the constructor to do:
DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[0].Value = "XYZ";
row.Cells[1].Value = 50.2;
dataGridView1.Rows.Add(row);
But getting exception on:
row.Cells[1].Value = 50.2;
Index was out of range. Must be non-negative and less than the size of the collection
Yes you should get an exception. Look at your code below. With row.Cells[1] you are actually referring to 2nd column in your gridview which apparently doesn't exists and so the end result.
row.Cells[1].Value = 50.2;
If you want to have another column to your grid then either add that using your designer surface (OR) create a DataTable with required columns and set that to DataSource of your gridview.
How to create a DataTable and attach it to GridView?
Search Google
EDIT:
In case you are still struggling understanding my comment then this is what I meant to say (sample code)
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("Message Subject");
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dr[dc] = "test";
DataRow dr1 = dt.NewRow();
dr1[dc] = "test123";
dt.Rows.Add(dr);
dt.Rows.Add(dr1);
this.dataGridView1.DataSource = dt;
}

Is it possible to put temporary data into datagridview without any datasource

I want to put my data into data grid view, by manually adding columns in it, so how can i do that,please help me.
Thank You in Advance.
Try the following that might solve your problem:
Ensure that the gridview(assuming he ID="gridview1") is in the markup and that AutoGenerateColumns="True"
DataTable dataTable = new dataTable();
dataTable.Columns.Add("Column1");
dataTable.Columns.Add("Column2");
dataTable.Columns.Add("Column3");
DataRow dataRow = dataTable.NewRow();
dataRow["Column1"] = "";
dataRow["Column2"] = "";
dataRow["Column3"] = "";
dataTable.Rows.Add(dataRow);
gridview1.DataSource = datatable;
gridview1.DataBind();
What about something like:
var grd = new GridView();
grd.AutoGenerateColumns = false;
BoundField field = new BoundField();
field.DataField = "CustomerName";
field.HeaderText = Resources.GlobalResources.Customer;
DataControlField col = field;
grd.Columns.Add(col);
grd.DataSource = sortedCustomers;
grd.DataBind();

Editing the DataSource of a ComboBox

I have a ComboBox with its DataSource set to an instance of a DataTable. When rows are added to the DataTable, they show in the ComboBox without additional code, but when a row is deleted, the ComboBox remains unchanged. A short summary of my code:
ComboBox selector = new ComboBox();
DataTable tbl = new DataTable();
PopulateTable()
{
DataRow row1 = tbl.NewRow();
row1["field1"] = 1;
row1["field2"] = "Some Text";
tbl.Rows.Add(row1);
DataRow row2 = tbl.NewRow();
row2["field1"] = 2;
row2["field2"] = "More Text";
tbl.Rows.Add(row2);
}
PopulateSelector()
{
selector.DisplayMember = "field2";
selector.ValueMember = "field1";
selector.DataSource = tbl;
}
RemoveRow()
{
tbl.Rows[0].Delete();
}
At this point, the ComboBox appears to be correct, but clicking it resets it to its previous data. The DataTable remains correct, deleting the row causes no problem in that instance, I just can't make the ComboBox reflect the changes.
Try this:
PopulateSelector()
{
selector.DataSource = null;
selector.DisplayMember = "field2";
selector.ValueMember = "field1";
selector.DataSource = tbl;
}
RemoveRow()
{
tbl.Rows[0].Delete();
PopulateSelector()
}
You can use a bindingsource inbetween the datatable and the combobox and call ResetBindings

How to add a new row to datagridview programmatically

if add row to DataTable
DataRow row = datatable1.NewRow();
row["column2"]="column2";
row["column6"]="column6";
datatable1.Rows.Add(row);
How about DataGridView??
You can do:
DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone();
row.Cells[0].Value = "XYZ";
row.Cells[1].Value = 50.2;
yourDataGridView.Rows.Add(row);
or:
DataGridViewRow row = (DataGridViewRow)yourDataGridView.Rows[0].Clone();
row.Cells["Column2"].Value = "XYZ";
row.Cells["Column6"].Value = 50.2;
yourDataGridView.Rows.Add(row);
Another way:
this.dataGridView1.Rows.Add("five", "six", "seven","eight");
this.dataGridView1.Rows.Insert(0, "one", "two", "three", "four");
From: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.rows.aspx
Like this:
var index = dgv.Rows.Add();
dgv.Rows[index].Cells["Column1"].Value = "Column1";
dgv.Rows[index].Cells["Column2"].Value = 5.6;
//....
Lets say you have a datagridview that is not bound to a dataset and you want to programmatically populate new rows...
Here's how you do it.
// Create a new row first as it will include the columns you've created at design-time.
int rowId = dataGridView1.Rows.Add();
// Grab the new row!
DataGridViewRow row = dataGridView1.Rows[rowId];
// Add the data
row.Cells["Column1"].Value = "Value1";
row.Cells["Column2"].Value = "Value2";
// And that's it! Quick and painless... :o)
Like this:
dataGridView1.Columns[0].Name = "column2";
dataGridView1.Columns[1].Name = "column6";
string[] row1 = new string[] { "column2 value", "column6 value" };
dataGridView1.Rows.Add(row1);
Or you need to set there values individually use the propery .Rows(), like this:
dataGridView1.Rows[1].Cells[0].Value = "cell value";
Adding a new row in a DGV with no rows with Add() raises SelectionChanged event before you can insert any data (or bind an object in Tag property).
Create a clone row from RowTemplate is safer imho:
//assuming that you created columns (via code or designer) in myDGV
DataGridViewRow row = (DataGridViewRow) myDGV.RowTemplate.Clone();
row.CreateCells(myDGV, "cell1", "cell2", "cell3");
myDGV.Rows.Add(row);
This is how I add a row if the dgrview is empty: (myDataGridView has two columns in my example)
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(myDataGridView);
row.Cells[0].Value = "some value";
row.Cells[1].Value = "next columns value";
myDataGridView.Rows.Add(row);
According to docs: "CreateCells() clears the existing cells and sets their template according to the supplied DataGridView template".
If the grid is bound against a DataSet / table its better to use a BindingSource like
var bindingSource = new BindingSource();
bindingSource.DataSource = dataTable;
grid.DataSource = bindingSource;
//Add data to dataTable and then call
bindingSource.ResetBindings(false)
here is another way to do such
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.ColumnCount = 3;
dataGridView1.Columns[0].Name = "Name";
dataGridView1.Columns[1].Name = "Age";
dataGridView1.Columns[2].Name = "City";
dataGridView1.Rows.Add("kathir", "25", "salem");
dataGridView1.Rows.Add("vino", "24", "attur");
dataGridView1.Rows.Add("maruthi", "26", "dharmapuri");
dataGridView1.Rows.Add("arun", "27", "chennai");
}
If you need to manipulate anything aside from the Cell Value string such as adding a Tag, try this:
DataGridViewRow newRow = (DataGridViewRow)mappingDataGridView.RowTemplate.Clone();
newRow.CreateCells(mappingDataGridView);
newRow.Cells[0].Value = mapping.Key;
newRow.Cells[1].Value = ((BusinessObject)mapping.Value).Name;
newRow.Cells[1].Tag = mapping.Value;
mappingDataGridView.Rows.Add(newRow);
If you are binding a List
List<Student> student = new List<Student>();
dataGridView1.DataSource = student.ToList();
student .Add(new Student());
//Reset the Datasource
dataGridView1.DataSource = null;
dataGridView1.DataSource = student;
If you are binding DataTable
DataTable table = new DataTable();
DataRow newRow = table.NewRow();
// Add the row to the rows collection.
table.Rows.Add(newRow);
yourDGV.Rows.Add(column1,column2...columnx); //add a row to a dataGridview
yourDGV.Rows[rowindex].Cells[Cell/Columnindex].value = yourvalue; //edit the value
you can also create a new row and then add it to the DataGridView like this:
DataGridViewRow row = new DataGridViewRow();
row.Cells[Cell/Columnindex].Value = yourvalue;
yourDGV.Rows.Add(row);
If anyone wanted to Add DataTable as a source of gridview then--
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("column1"));
dt.Columns.Add(new DataColumn("column2"));
DataRow dr = dt.NewRow();
dr[0] = "column1 Value";
dr[1] = "column2 Value";
dt.Rows.Add(dr);
dataGridView1.DataSource = dt;
An example of copy row from dataGridView and added a new row in The same dataGridView:
DataTable Dt = new DataTable();
Dt.Columns.Add("Column1");
Dt.Columns.Add("Column2");
DataRow dr = Dt.NewRow();
DataGridViewRow dgvR = (DataGridViewRow)dataGridView1.CurrentRow;
dr[0] = dgvR.Cells[0].Value;
dr[1] = dgvR.Cells[1].Value;
Dt.Rows.Add(dR);
dataGridView1.DataSource = Dt;
Consider a Windows Application and using Button Click Event put this code in it.
dataGridView1.Rows
.Add(new object[] { textBox1.Text, textBox2.Text, textBox3.Text });
//Add a list of BBDD
var item = myEntities.getList().ToList();
//Insert a new object of type in a position of the list
item.Insert(0,(new Model.getList_Result { id = 0, name = "Coca Cola" }));
//List assigned to DataGridView
dgList.DataSource = item;
//header
dataGridView1.RowCount = 50;
dataGridView1.Rows[0].HeaderCell.Value = "Product_ID0";
//add row by cell
dataGridView1.Rows[1].Cells[0].Value = "cell value";
If you´ve already defined a DataSource, You can get the DataGridView´s DataSource and cast it as a Datatable.
Then add a new DataRow and set the Fields Values.
Add the new row to the DataTable and Accept the changes.
In C# it would be something like this..
DataTable dataTable = (DataTable)dataGridView.DataSource;
DataRow drToAdd = dataTable.NewRow();
drToAdd["Field1"] = "Value1";
drToAdd["Field2"] = "Value2";
dataTable.Rows.Add(drToAdd);
dataTable.AcceptChanges();
I think the cleanest way to do is invoking the DataGridView and using a lambda expression. Simple one liner while also keeping the code thread safe:
MyDataGridView.Invoke((MethodInvoker)(() => MyDataGridView.Rows.Add(param1, param2, paramX)));
I have found this useful more than once when the DataGrid is bound to a table.
DataTable dt = (DataTable)dgvData.DataSource;
DataRow row = dt.NewRow();
foreach (var something in something)
{
row["ColumnName"] = something ;
}
dt.Rows.Add(row);
dgvData.DataSource = dt;
string[] splited = t.Split('>');
int index = dgv_customers.Rows.Add(new DataGridViewRow());
dgv_customers.Rows[index].Cells["cust_id"].Value=splited.WhichIsType("id;");
But be aware, WhichIsType is the extension method I created.

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