I have a sql statemente but I don't want to display all info in the gridview (c# webforms). How to bind specific columns at runtime on gridview?
Thanks
First of all I'd edit columns in Visual Studio Designer so I would get exact columns I want.
It depends how do you fetch data into DataGrid. If you use SqlDataSource I would recommend make a close up on Selecting event. In other case (SqlDataReader) I'd make binding while reading. Or you can also use Linq to Entity to get values what you want, just like this:
var name = from names in context.data_table
select names;
gridview.datasource = name;
You can create the columns for the DataGridView yourself. Example:
DataGridView dataGridView1 = new DataGridView();
BindingSource bindingSource1 = new BindingSource();
dataGridView1.ColumnCount = 2;
dataGridView1.Columns[0].Name = "FieldA";
dataGridView1.Columns[0].DataPropertyName = "FieldA";
dataGridView1.Columns[1].Name = "FieldB";
dataGridView1.Columns[1].DataPropertyName = "FieldB";
bindingSource1.DataSource = GetDataTable();
dataGridView1.DataSource = bindingSource1;
Be sure to Data Bind your grid after you set a Data Source like shown above. Best of luck!
Entities entities = ObjectContextManager.GetCurrentContext<AdHocReportingEntities>();
var users = from e in entities.Users
where e.State == userState'
orderby e.Name
select new { e.Name, e.State};
Grid.DataSource = users;
Grid.DataBind();`
Related
I have some table from a dataSet in a reportViewer (winform), and some ComboBox. I want the ComboBox's dataSource to be a list of the table column names. How can I do that?
Assuming you have a data table in table variable, then to show list of it's columns in a ComboBox you can use a code like this:
comboBox1.DataSource = table.Columns.Cast<DataColumn>().ToList();
comboBox1.ValueMember = "ColumnName";
comboBox1.DisplayMember = "ColumnName";
you can try this also
comb.DataSource = dt;
comb.ValueMember = dt.Columns[0].ColumnName.ToString();
comb.DisplayMember = dt.Columns[1].ColumnName.ToString();
I bind a datagridview from a linq query, but I don't know how to make it updated to database when users makes changes on the datagridview.
var q = from w in dowacodbEntities.worksheets
where w.ContractForm_id.Equals(g_ContractID)
orderby w.id
select new
{
w.id,
w.UnitPrice,
w.LabourCost
};
BindingSource bindingSource = new BindingSource(); // use bindingsource
bindingSource.DataSource = q.ToList(); // convert linq query to bindingsource
dataGridView1.DataSource = bindingSource; // add bindingsource to datagridview
p/s : I'm using C# winform
I think this is the same problem
WinForms DataGridView - update database
I am trying to remove all the rows to reload them (I need to remove all rows) For some reason its not removing them from my datagridview (tho its not adding any extra either) nothing is happening. I have tried many different methods, I know I have done this in the past. (maybe because its end of the day)
Here is my code trying a whole bunch of removes
private void loadMSXGridView()
{
BindingSource bs = new BindingSource();
dgv.DataSource = null;
dgv.Refresh();
bs.DataSource = GetTable();
dgv.DataSource = bs;
dgv.Columns[0].Width = 391;
dgv.Columns[1].Width = 30;
}
private DataTable GetTable()
{
DataTable t = new DataTable();
t.Rows.Clear();
t.AcceptChanges();
t.Columns.Add("Accounting Line", typeof(string));
t.Columns.Add("#", typeof(string));
foreach (AMAPnr.RemarkElement re in AMAPnr._RemarkElements)
{
if (re.ElementID == "RM" && re.FreeFlow.StartsWith("*MS"))
{
DataGridViewCell gridCellText;
DataGridViewCell gridCellElement;
gridCellText = new DataGridViewTextBoxCell();
gridCellText.Value = re.FreeFlow;
gridCellElement = new DataGridViewTextBoxCell();
gridCellElement.Value = re.ElementNo.ToString();
t.Rows.Add(gridCellText.Value, gridCellElement.Value);
}
}
return t;
}
My delete button calls loadMSXGridView, I only need to refresh everything because the items in my datagridview are associated to an element number, which won't remain the same
Initially, you are data-binding:
dgv.DataSource = GetTable();
you should then continue data-binding; either tell the table to clear itself (and repopulate the data), or just assign a different data-table to dgv.DataSource.
In my limited data binding experience it is not easy to edit a data source. You should handle your data edits using one of the row binding or other events. However if you want to edit a datasource you basically have to clone the structure, then import the rows. So in this sense you should actually go back to your datasource and select exactly what you want.
However..
If you want to filter / edit your data here is how you can do it:
DataSet ds1 = [Your Data Source]
DataSet ds2 = new DataSet();
ds2 = ds1.Clone();
for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
{
if (ds1.Tables[0].Rows[i].ItemArray[0].ToString() != "SomeValue")
{
ds2.Tables[0].ImportRow(ds1.Tables[0].Rows[i]);
}
}
ds1 = ds2;
If you simply just want to add a different datatable as the datasource, then do:
datagridview.DataSource = datatable;
datagridview.Invalidate();
That should work, as I have just done the exact same thing on a project i'm working on at the minute :)
My fault, everything worked after running a throughough debug I found
The remarks elements were not being deleted, thus it was getting deleted by adding the same items back in. I remove the items from the RemarkElement section and it works, thanks for your help everyone!
I would suggest to set the DataSource of your DataGridView to a BindingSource and change the DataSource of the BindingSource instead:
var table1 = GetDataTable();
var bindingSource1 = new BindingSource(table1, null);
dataGridView1.DataSource = bindingSource1;
// after reload
var table2 = GetDataTable();
bindingSource1.DataSource = table2;
that solves most problems, since you don't have to worry about how your data is bound.
I have a ComboBox with its elements loaded from a sqlserver table (groups).
I also have a DataGridView, linked to another table (users).
When I load the form, the combo is filled with groups, and the datagridview is filled with users (all the users)
1) I want to be able to select a group from the ComboBox (dropDownList), and then to refresh the DataGridView with the users that belong to that selected group...
2) And How can I show a join relation in the DataGridView? Let's say I want to show the groupName in the last column of the each user...
PS:
I have an xsd Dataset created in my VS2008 project with its
corresponding tableAdapters generated
(groupTableAdapter, userTableAdapter)
and some sql-methods added to each
adapter
1) Set up a BindingSource for both tables.
BindingSource bsGroup = new BindingSource();
BindingSource bsUser = new BindingSource();
bsGroup.DataSource = MyDataSet.Tables["Group"];
bsUser.DataSource = MyDataSet.Tables["User"];
2) Set up your Combo and Grid DataSources.
MyCombo.DataSource = bsGroup;
MyCombo.DisplayMember = "GroupName"; // whatever your ColumnName is
MyCombo.ValueMember = "GroupID";
MyGrid.DataSource = bsUser;
3) Set up a SelectedIndexChanged event for the Combo and use it to change the filter on the bsUser bindingsource.
MyCombo.SelectedIndexChanged += new System.EventHandler(MyCombo_SelectedIndexChanged);
private void MyCombo_SelectedIndexChanged(object sender, System.EventArgs e)
{
// this will depend on what your column names are, obviously
string filter = string.Format("GroupID = {0}", MyCombo.SelectedValue);
bsUser.Filter = filter;
}
This worked fine... taken from here.
(Yes, I posted this also on MSDN because I was in a hurry)
Using c# .net 2.0 , I want to bind a textbox to a specific row of my table. In Example :
Table Person
ID NAME PRENOM SPECIAL_CATEGORY
1 BOB BOB mex
2 AL AL tot
3 PO PO pap
I want to bind my textbox on the field name where the row contains special_categeory = 'tot'.
Is it possible? or I need to create a Datarow for this row and binding it.
Assuming you're talking about Winforms and you have your data source as a component on your form already, this is fairly simple.
Drag a new BindingSource onto your form and set its data source to be whatever your existing data source is. You can then specify a filtering expression in the new BindingSource's Filter property in the designer. Bind your TextBox to your new BindingSource and you're all set.
Doing this manually (without the designer) is only marginally more complicated.
BindingSource newSource = new BindingSource();
newSource.DataSource = yourExistingDataSource;
newSource.Filter = "special_categeory = 'tot'";
textBox.DataBindings.Add("Text", newSource, "DataMember");
You should be able to bind via...
myNameTextBox.DataBindings.Add( "Text", MyTable, "NAME" );
myPrenomTextBox.DataBindings.Add( "Text", MyTable, "PRENOM" );
mySpecial_CategoryTextBox.DataBindings.Add( "Text", MyTable, "SPECIAL_CATEGORY" );
I actually have a framework that scrolls through all controls, and if they match a column name in a given table, they immediately bind themselves like above.
Then, when you scroll the grid, it should also refresh the individual text controls in your form too.
If there is some binding that needs to be done, you can follow this pattern:
DataView dv = new DataView(MyTable);
dv.RowFilter = "SPECIAL_CATEGORY = 'tot'";
GridView1.DataSource = dv;
GridView1.DataBind();
But I don't think you bind to a TextBox? You can set the Text property like:
foreach(DataRow dr in MyTable.Rows)
{
if (dr["SPECIAL_CATEGORY"] != DBNull.Value &&
dr["SPECIAL_CATEGORY"].ToString() == "tot")
{
myTextBox.Text = dr["NAME"].ToString()
break;
}
}
I'm going to assume it's Winforms and this is how you can do it:
myTable.DefaultView.RowFilter = "SPECIAL_CATEGORY = 'tot'";
this.textBox1.DataBindings.Add("Text",myTable.DefaultView,"Name");