c# Binding on specific row in table - c#

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");

Related

Replace int column in Data Table with combobox for DataGridView (Winforms)

I have a DataTable with some integer values (assume 0 => 'open', 1 => 'proceeding', 2 => 'free' etc.) and in a dgv I want to allow the user to change that value, but with a combobox and with string values. So I created to test this a simple winform app
public Form1()
{
InitializeComponent();
DataTable dt = new DataTable();
dt.Columns.Add("test");
dt.Rows.Add(1);
dt.Rows.Add(2);
DataTable source = new DataTable();
source.Columns.AddRange(new DataColumn[] { new DataColumn("Value", typeof(int)), new DataColumn("Display", typeof(string)) });
source.Rows.Add(0, "zero");
source.Rows.Add(1, "one");
source.Rows.Add(2, "two");
dataGridView1.DataSource = dt;
var testTextColumn = new DataGridViewComboBoxColumn();
testTextColumn.HeaderText = "Text";
testTextColumn.Name = "testText";
testTextColumn.DataSource = source;
testTextColumn.DisplayMember = "Display";
testTextColumn.ValueMember = "Value";
dataGridView1.Columns.Add(testTextColumn);
}
So far so good, I thought I could simply make the test column invisible and only have the testText column visible (in the final app), but how does one combine the to values, i.e. when I change something in the cb update the value of the datatable? I could do it by changeEvents, but that seems rather impractical. Is there some sort of databinding?
There are three (3) things wrong in your posted code to achieve what you describe.
1-The line of code…
dt.Columns.Add("test");
… is defaulting to a string value. Therefore, the combo box would throw a DataError when you try to bind the “Value” column from the source table. So, you need to specify the int type column in the data. Like…
dt.Columns.Add("test", typeof(int));
2- Before the code set the grids DataSource the code needs to specify that we do NOT want the grid to AutoGenerateColumns. Otherwise, we will end up with two columns. In addition, this grid property is NOT a displayed property in the “Designer.” You will need to set this property BEFORE you add the data source and you need to set this property in your code. Something like…
dataGridView1.AutoGenerateColumns = false;
3- When the code creates the combo box column, it never identifies “which” column in the grids DataSource we want to bind the combo box column to. That is the purpose of the columns DataPropertyName. So, you need to add this line of code in the combo box definition…
testTextColumn.DataPropertyName = "test";
Making these changes, should display only the combo box column.
creates a cell change event, then takes the number of the row you changed and you have access to the columns with the indexes ...
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentRow != null)
{
DataGridViewRow dgvRow = dataGridView1.CurrentRow;
// do what u want here like
int teste = Convert.ToInt32(dgvRow.Cells[1].Value);
}
}

Can't Add ComboBox to Radgrid

[View][1]I'm creating a bounded radgrid, i was trying to add bounded combobox to rad grid, but column is showing.combobox are't show.
You can find various samples for using RadGrid in combination with combo/dropdownlist provided in this post.
First: you need to be a little more explicit in your question or problem.
Maybe adding a little code or images will help us understand more.
From what i understand, you have a radgridview and you want a specific column to have a combobox as a type.
You can do something like this:
//define a GridViewMultiComboBoxColumn
GridViewMultiComboBoxColumn column = new GridViewMultiComboBoxColumn();
column.Name = "Your column name";
column.HeaderText = "The header text you want to have";
column.FieldName = "Field name, maybe you have a class read from a db";
column.DataSource = ds; //here you need to define your datasource for your combobox
column.ValueMember = "Value"; //depends on what you receive from datasource
column.DisplayMember = "Value"; //depends on what you receive from datasource
//add the column to your radgridview
gridView.MasterTemplate.Columns.Add(column);

How to add ComboBox to WINFORM datagridview bound to datatable

I'm a SQL DBA with low skill level in VS C# and Winforms. I've been struggling with adding a combo box to a DataGridView column for several days and have given up. I have a datatable dt1 and datagridview dg1. dg1.Datasource = dt1; dt1 is a member of dataset ds1. I am providing combo items from an array.
I have tried autogeneration true and false.
If autogeneration=true I get two columns of the same name with 1 combo box and it's in the wrong column position and I get correct data from dt1
If false and I programmatically define columns for dg1, I don't get any data from dt1.
What should my code look like and what possible bindings or properties am I missing so that I add a combo box for 'GRADE' in the 4th column position and dg1 populates from dt1 and combo from array.
Totally frustrated after reading dozens of blogs and trying things for several days. Please help.
private DataGridViewComboBoxColumn CreateComboBox()
{
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
{
combo.Name = "comboColumn";
combo.HeaderText = "Grade";
ArrayList drl = new ArrayList();
drl.Add("GS1");
drl.Add("GS2");
drl.Add("WG1");
drl.Add("WG2");
combo.Items.AddRange(drl.ToArray());
combo.DataSource = drl;
//combo.ValueMember = "EmployeeID";
//combo.DisplayMember = "Grade";
//combo.DataPropertyName = "Grade";
}
return combo;
}
public Employee()
{
InitializeComponent();
WindowState = FormWindowState.Maximized;
Ds1 = new DataSet("ds1");
Dt1 = new DataTable("dt1");
ds1.Tables.Add(dt1);
dt1.Columns.Add("EmployeeID");
dt1.Columns.Add("FirstName");
dt1.Columns.Add("LastName");
dt1.Columns.Add("Grade");
dt1.Columns.Add("DOB");
//initialize datagridview
Dg1.AutoGenerateColumns = true;
//dg1.Columns.Add("column4", " EmployeeID ");
// dg1.Columns.Add("column4", " FirstName ");
// dg1.Columns.Add("column4", " LastName ");
Dg1.Columns.Add(CreateComboBox());
// dg1.Columns.Add("column5", " DOB ");
Dg1.DataSource = dt1;
}
Resolved: After several days hunting and trying, I tried a solution I didn't think would work because it mentioned an unbound column and appeared to require a SQL or some other connection make it a bound column. Turns out it isn't necessary to bind the columns. Here is what you do.
1.Open your Form designer an place Focus on your DataGridView and select properties.
2.Scroll down to the Columns collection (mine was at the bottom under Misc.) and expand the collection.
3.Add Column name and if binding to DataTable set the DataPropertyName to the dt column. In my case I set both the same.
Also there is a drop down to choose the ColumnType
4.Add your ComboBox column. This has a few more settings. You should look through all of them but I was interested in Items &
HeaderText only. I set HeaderText the same as ColumnName &
DataPropertyName. I then opened the Items and added my list.
There is also a DataSource. I presume that is for populating your
ComboBox from a database, service, or sharepoint but I'm not doing
that.
5.That's it.
In your .cs code file you need to insert two lines of code. I placed mine at the top of the form where I declare datatables I need available to all methods.
<yourdatagridview>.AutoGenerateColumns = false;
<yourdatagridview>.DataSource = <yourdatatable>;

Fill DataGridView on condition from database

I have MySQL database and a DataGridView in C# and to fill the DataGridView I do the following:
schoolDataSet schl = new schoolDataSet();
schoolDataSetTableAdapters.studentinfoTableAdapter adptr = new schoolDataSetTableAdapters.studentinfoTableAdapter();
adptr.Fill(schl.studentinfo);
dataGridView1.DataSource = schl.studentinfo.DefaultView;
and undesired columns I make them visible = false from DataGridView properties but I came with a problem if I want to specify what data (rows) to fill in DataGridView such applying a where condition like:
fill data in DataGridView WHERE IsActive = 1 so can I still use the above code with some modifications or I have to write SQL query and fill the DataGridView manually ?
After searching and trying tons of codes I got it as following in simplest code:
In the code above just comment out last line which is dataGridView1.DataSource = schl.studentinfo.DefaultView; or simply replace it with the following
DataView dv = new DataView(schoolDataSet.studentinfo, "IsActive = 'false'", "id", DataViewRowState.CurrentRows);
Which creates a new DataView and filters according to IsActive column with false value, the third parameter id is to sort based-on, and finally you can write another line
dataGridView1.DataSource = dv; that will tell the DataGridView to load data from DataView.
Hope to save someone's time.
Big thanks goes to #Karthik Ganesan

c# Gridview - Bind selected columns from datareader

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();`

Categories

Resources