fill combobox using bindingsource - winforms

on windows form all textbox and combobox is bind from acctPackageBindingSource . My problem with biniding in combobox that display only int value means that is coming form acctPackage . And i want to display the name means 'Displaymember' of that value . That one is coming form different table name is sysCode. So how can i display the display member perfectly . Below is my code
// Here the all value is coming form Syscode table .
public void FillDropDown()
{
if (_commonComponent == null)
_commonComponent = new CommonComponent();
List<SysCode> _syscode = _commonComponent.GetByTableCodeForIncomeDedMapping("19");
bindingSourceSysCode.DataSource = _syscode;
packageCodeComboBox.DataSource = bindingSourceSysCode;
packageCodeComboBox.DisplayMember = "Desclong2";
packageCodeComboBox.ValueMember = "PackageCode";
}
//This part is bind my all value on the form
private void FillAcctPackage()
{
if (_commonComponent == null)
_commonComponent = new CommonComponent();
acctPackageBindingSource.DataSource = _commonComponent.GetAcctPackge();
}

Related

How to determine the column name to read value from a list in c# at run time?

I have a datagridview (DGV) which contains some columns and a generic list which contains the focus information for all those columns available in the DGV. Now when I enter e cell in DGV, I want to get it's focus information from the list in a string variable. I am receiving the DGVs currentCell and fieldName (DGVs column name for which I want to load focus info) as input parameters. Below is my code:
private Rectangle GetFocusSettingsForField(string fieldName, DataGridViewCell currentCell)
{
NA27Bo bo = new NA27Bo();
Rectangle rectangle = new Rectangle();
string projectId = dgvEntryVerify["ProjectId", currentCell.RowIndex].Value.ToString();
string batchId = dgvEntryVerify["BatchId", currentCell.RowIndex].Value.ToString();
string imageId = dgvEntryVerify["ImageId", currentCell.RowIndex].Value.ToString();
string noOnImage = dgvEntryVerify["NumberOnImage", currentCell.RowIndex].Value.ToString();
int serialNo = Convert.ToInt32(dgvEntryVerify["SerialNumber", currentCell.RowIndex].Value.ToString());
PropertyInfo[] properties = bo.GetType().GetProperties();
string actualFieldName = "";
for (int i = 0; i < properties.Length; i++)
{
if (properties[i].Name.Contains(fieldName + "Focus"))
{
actualFieldName = properties[i].Name;
}
}
// Here I want to get the data from property "actualFieldName" of the list
//string value = data from property "actualFieldName" of the list
}
I am using VS2012, C#, Winforms but Framework 2.0 (framework can't be changed).

DataGridViewComboBoxCell Value Not Updating When Set Programmatically C# Winforms

I've read all the similiar posts about this darn control (DataGridViewComboBoxCell) and setting it's value programmatically but implementing all the suggestions hasn't worked. I could probably change the UI to get around this problem but I don't like to be beat!
private void PopulateAreaForRoleAssociation()
{
// If businessRoleList is null then no data has been bound to the dgv so return
if (businessRoleList == null)
return;
// Ensure businessArea repository is instantiated
if (businessAreaRepository == null)
businessAreaRepository = new BusinessAreaRespository();
// Get a reference to the combobox column of the dgv
DataGridViewComboBoxColumn comboBoxBusinessAreaColumn = (DataGridViewComboBoxColumn)dgvBusinessRole.Columns["BusinessArea"];
// Set Datasource properties to fill combobox
comboBoxBusinessAreaColumn.DisplayMember = "Name";
comboBoxBusinessAreaColumn.ValueMember = "Id";
comboBoxBusinessAreaColumn.ValueType = typeof(Guid);
// Fill combobox with businessarea objects from list out of repository
comboBoxBusinessAreaColumn.DataSource = businessAreaRepository.GetAll();
// loop through the businessRoles list which the dgv is bound to and get out each dgv row based upon the current id in the loop
businessRoleList.Cast<BusinessRole>().ToList().ForEach(delegate(BusinessRole currentRole)
{
DataGridViewRow currentRowForRole = dgvBusinessRole.Rows.Cast<DataGridViewRow>().ToList().Find(row => ((BusinessRole)row.DataBoundItem).Id == currentRole.Id);
// Get a reference to the comboBox cell in the current row
DataGridViewComboBoxCell comboBoxCell = (DataGridViewComboBoxCell)currentRowForRole.Cells[2];
// Not sure if this is necessary since these properties should be inherited from the combobox column properties
comboBoxCell.DisplayMember = "Name";
comboBoxCell.ValueMember = "Id";
comboBoxCell.ValueType = typeof(Guid);
// Get the business area for the current business role
BusinessArea currentAreaForRole = businessAreaRepository.FetchByRoleId(currentRole.Id);
// if the role has an associated area then set the value of the cell to be the appropriate item in the combobox
// and update the cell value
if (currentAreaForRole != null)
{
foreach (BusinessArea area in comboBoxCell.Items)
{
if (currentAreaForRole.Id == area.Id)
{
comboBoxCell.Value = area.Id;
dgvBusinessRole.UpdateCellValue(2, comboBoxCell.RowIndex);
}
}
}
});
}
The dgv is first bound to a binding list holding BusinessRole objects, then the combobox column is bound to a basic list of BusinessArea objects that come out of a repository class. I then loop through the bindinglist and pull out the row of the dgv that is bound to the current item in the bindinglist loop.
With that row I make a database call to see if the BusinessRole entity is associated with a BusinessArea entity. If it is then I want to select the item in the combobox column that holds the BusinessAreas.
The problem is that when the grid is loaded, all the data is there and the comboboxes are populated with a list of available areas, however any values that are set are not displayed. The code that sets the value is definately getting hit and the value I am setting definately exists in the list.
There are no data errors, nothing. It's just refusing to update the UI with the value I programmatically set.
Any help would be greatly appreciated as always.
Thanks
This code works for my first combo box I have in my row with the following code, but I try it with the next one in the row and it doesn't work. I could use the help with the rest I have 3 more to do. I do set the combo boxes on a second form from this form with the same code as is on the last line of the try block but using the cell information instead of the dataset
try
{
string strQuery = "select fundCode from vwDefaultItems where IncomeType = '" + stIncome + "'";
SqlDataAdapter daDefault = new SqlDataAdapter(strQuery, conn);
DataSet dsDefault = new DataSet();
daDefault.Fill(dsDefault);
strDefFund = dsDefault.Tables[0].Rows[0].ItemArray[0].ToString();
dgvCheckEntry.Rows[curRow].Cells[7].Value = dsDefault.Tables[0].Rows[0].ItemArray[0].ToString();
}
catch (Exception eq)
{
}

Get the primarykey on radio button click

I have several radio buttons that are dynamically populated on a form and I have set a click event on the dynamically created radio buttons. On click i get a returned value as follows through debugging (eg) "sender { Text = "this is answer one" + Checked = "True"} using code as follows:
//Radio button click:
void Form1_Click(object sender, EventArgs e)
{
RadioButton rb = sender as RadioButton;
string radioButtonValue = rb.Text;
if (radioButtonValue != String.Empty)
{
}
}
The debug values are returned via "RadioButton rb = sender as RadioButton;" - the diffrent radio buttons text is set via a dataset that I call in a local dataset that loops through the dataset and and sets the radio button text accordingly (eg):
for (int i = 0; i < _dataSetRadioButtons.Tables["tbl_QuestionnaireAnswer"].Rows.Count; i++)
{
radioButtons[i] = new RadioButton();
radioButtons[i].AutoCheck = true;
radioButtons[i].Text = _dataSetRadioButtons.Tables["tbl_QuestionnaireAnswer"].Rows[i]["tbl_QuestionnaireAnswer_Description"].ToString();
radioButtons[i].Location = new System.Drawing.Point(60, 20 + i * 20);
radioButtons[i].Click += new EventHandler(Form1_Click);
panel.Controls.Add(radioButtons[i]);
}
So: wat id like to know is on the radio button click (Form1_Click) event is it possible to return the primary key of the of the selected radio button that I choose and not just the sender { Text = "this is answer one" + Checked = "True"} as I would like to use the primarykey in that dataset to write back to my Database.
Thanks in advance.
Kind regards
geo
Most winforms controls contain the Tag property that is used to contain custom user data in the control. You can read more at: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.tag.aspx
So, your solution should be simpler and more concise like this:
for (int i = 0; i < _dataSetRadioButtons.Tables["tbl_QuestionnaireAnswer"].Rows.Count; i++)
{
radioButtons[i] = new RadioButton();
radioButtons[i].AutoCheck = true;
radioButtons[i].Location = new System.Drawing.Point(60, 20 + i * 20);
radioButtons[i].Tag = _dataSetRadioButtons.Tables["tbl_QuestionnaireAnswer"].Rows[i];
radioButtons[i].Click += new EventHandler(Form1_Click);
panel.Controls.Add(radioButtons[i]);
}
This includes a relevant datarow in the radiobutton. The next thing is to get any data from it you need:
//Radio button click:
void Form1_Click(object sender, EventArgs e)
{
RadioButton radioButton = sender as RadioButton;
if (radioButton == null)
return;
DataRow row = radioButton.Tag as DataRow;
if (row == null)
return;
/* Post any processing here. e.g.
MessageBox.Show(row["ID"].ToString());
*/
}
This way you have all the data and it's strongly typed, which is a good thing.

DataSet created in code not Binding to ListView

I have a WPF User Control with a ListView in it that is created based on the DataSet that is passed to it:
public void PopulateList(DataSet ds) {
listView.View = CreateGridViewColumns(ds.Tables[0]);
listData.DataContext = ds.Tables[0];
}
private GridView CreateGridViewColumns(DataTable dt) {
// Create the GridView
var gv = new GridView {AllowsColumnReorder = true};
// Create the GridView Columns
foreach (DataColumn item in dt.Columns) {
var gvc = new GridViewColumn
{
DisplayMemberBinding = new Binding(item.ColumnName),
Header = item.ColumnName,
Width = Double.NaN
};
gv.Columns.Add(gvc);
}
return gv;
}
Now I create the user control in code and call it's PopulateList with the appropriate dataset and this is where the problems are starting:
If I pass in a dataset that was created from a call to the database the list view shows all the data but if i pass in a DataSet that i created in code the ListView shows the Columns but will not show the data
//This is a function that hides the DB call return type is DataSet
var dsPatientSmokingStatusHistory = DataRepository.PatientSmokingStatusProvider.GetHistory(PatientId);
//radGridViewPatientSmokingStatus.DataSource = dsPatientSmokingStatusHistory.Tables[0];
var dt = new DataTable();
string c1 = "Date".PadLeft(23).PadRight(23);
string c2 = "Status".PadLeft(20).PadRight(50);
dt.Columns.Add(c1);
dt.Columns.Add(c2);
int i = 0;
foreach (DataRow row in dsPatientSmokingStatusHistory.Tables[0].Rows) {
var dataRow = dt.NewRow();
dataRow[c1] = ((DateTime)row["Date"]).ToString("MM/dd/yyyy");
dataRow[c2] = row["Status"].ToString();
dt.Rows.Add(dataRow);
dt.Rows[i].AcceptChanges();
i++;
}
DataSet ds = new DataSet();
dt.TableName = "Table";
ds.Tables.Add(dt);
ds.AcceptChanges();
smokingStatusGrid.GridWidth = 455;
smokingStatusGrid.GridHight = 97;
//This line does not show data
smokingStatusGrid.PopulateGrid(ds);
//This line will show data
smokingStatusGrid.PopulateGrid(dsPatientSmokingStatusHistory);
Is there a difference between these two datasets that i don't know about that is preventing me from databinding to it?
Also the user control is being used as an ElementHost in a WinForms application (not sure if this makes a difference)
Your code says:
DisplayMemberBinding = new Binding(item.ColumnName)
This binding constructor takes a string paramter which as per MSDN is "The initial Path for the binding" and is of datatype System.Windows.PropertyPath. I guess, since system tries to find a property with the same name in your class, and your string (item.ColumnName) has spaces at start, it runs into a problem (properties can't start with a space).
Would recommend you to take off the padding that you are doing in column name of your table. Apply any padding/margins in the Header of your GridView.

How can I databind dynamically loaded DataGridViews?

I'm developing a Windows Forms application in VS2008. I want to display a unknown, but small number of DataGridViews on a form, using code like this:
foreach (QueryFilter f in Query.Filter)
{
DataGridView grid = CreateGridView(String.Format("GridView{0}", filters.Count));
grid.Location = new System.Drawing.Point(3, 9 + (filters.Count * grid.Height + 9));
BindingList<QueryFilterNode> nodes = new BindingList<QueryFilterNode>();
foreach (QueryFilterNode node in f)
nodes.Add(node);
grid.DataSource = nodes;
panel1.Controls.Add(grid);
filters.Add(nodes);
}
The grid(s) are added to the panel, but the data inside is not displayed. My guess is setting the DataSource property doesn't actualy bind the grid, because (for example) the dataGridView_ColumnAdded event is not fired.
QueryFilter and QueryFilterNode are just POCO's and contain data of course.
For completeness sake the construction of the DataGridView:
private DataGridView CreateGridView(string name)
{
DataGridView grid = new DataGridView();
grid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
grid.Name = name;
grid.Size = new System.Drawing.Size(484, 120);
grid.ColumnAdded += new System.Windows.Forms.DataGridViewColumnEventHandler(this.dataGridView_ColumnAdded);
return grid;
}
Hmm, it seems it was my own mistake.
QueryFilterNode, used as datasource ( BindingList<QueryFilterNode> ) wasn't a POCO but a datacontract. Snippet:
[DataContract(Name = "QueryFilterNode")]
public class QueryFilterNode
{
[DataMember(IsRequired = true)]
public string FieldCode;
For some reason these cannot be databound. I used a simple class like this in my BindingList and it just worked.
class QueryFilterNodeSimple
{
public string FieldCode
{ get; set; }

Categories

Resources