How can Add items to Binded Datasource Combo Box? - winforms

Hi I am new to C#. I have tried following way to add new item to my bound ComboBox but it won't give any result.
Is it possible to add new item to bound ComboBox (Here Problem is ID is Bigint data type but I want to add Select ID)?
If it is possible, please provide piece of code
try
{
objSqlExecute.OpenConnection();
string strQuery = objQueryManager.GetEmployeeRecords();
//Add Extra Items to combo Box
cmbEmployeeID.Items.Add("Select Id");
DataTable dtEmployee = objSqlExecute.GetRecordExecution(strQuery);
// DataRow dtNew = dtEmployee.NewRow();
// dtNew["ID"] = "Select ID";
// dtNew["FName"] = "";
//dtEmployee.Rows.InsertAt(dtNew, 0);
cmbEmployeeID.DataSource = dtEmployee;
cmbEmployeeID.DisplayMember = "ID";
cmbEmployeeID.ValueMember = "FName";
}

try
{
objSqlExecute.OpenConnection();
string strQuery = objQueryManager.GetEmployeeRecords();
//Add Extra Items to combo Box
DataTable dtEmployee = objSqlExecute.GetRecordExecution(strQuery);
cmbEmployeeID.DataSource = dtEmployee;
cmbEmployeeID.DisplayMember = "ID";
cmbEmployeeID.ValueMember = "FName";
cmbEmployeeID.Items.Insert(0, "None Selected");
}

Did you try your query to make sure it returns values? returning multiple records, single or none?
Do you want to add ONE new item at random intervals?
Or else do you have an option to INSERT all items at once?
Can you try adding toString() for converting BigInt?
Notes:
The arcticle here gives an insight to add a new item to a combobox using sql.
Looking at the questions you are posting, to see a sample of how to use ListItems in this scenario, you could refer to the web link.

Related

Finding a ListView row in coded UI causes 'No row was specified as search container for the control.'

I have a ListView inside of a Popup control (seems to be significant that it's in a Popup). The coded test is pretty basic, click a ToggleButton to open the popup, and then select an item in the ListView.
Except it seems that it can't find the item in the ListView.
System.ArgumentException: No row was specified as search container for
the control. To search for a cell control using 'ColumnIndex', you
must specify row as a container element or add 'RowIndex' to the
search property of the cell. Parameter name: SearchProperties Result
StackTrace: at
Microsoft.VisualStudio.TestTools.UITesting.ALUtility.ThrowDataGridRelatedException(String
errorString, String propertyName) at
Microsoft.VisualStudio.TestTools.UITesting.WpfControls.WpfCell.GetUITestControlsForSearch()
at
Microsoft.VisualStudio.TestTools.UITesting.UITestControl.get_QueryId()
at
Microsoft.VisualStudio.TestTools.UITesting.UITestControlSearchArgument.get_SingleQueryString()
at
Microsoft.VisualStudio.TestTools.UITesting.SearchHelper.GetUITestControlRecursive(Boolean
useCache, Boolean alwaysSearch, ISearchArgument searchArg, IList`1
windowTitles, Int32& timeLeft)
The generated code is failing at this point
uIItemCell.Checked = this.MyListBoxCellParams.UIItemCellChecked;
where uIItemCell comes from this property
public WpfCell UIItemCell
{
get
{
if ((this.mUIItemCell == null))
{
this.mUIItemCell = new WpfCell(this);
#region Search Criteria
this.mUIItemCell.SearchProperties[WpfCell.PropertyNames.ColumnHeader] = null;
this.mUIItemCell.SearchProperties[WpfCell.PropertyNames.ColumnIndex] = "1";
this.mUIItemCell.WindowTitles.Add("CodedUITestWindow");
#endregion
}
return this.mUIItemCell;
}
}
So I guess this is where the criteria should be specified, but what how? And should row be hard coded somehow? Why didn't the test editor set the row?
If it helps, this is the .ctor where UIItemCell (above) is specified, seems like more search params
public UIMyCellDataItem(UITestControl searchLimitContainer) :
base(searchLimitContainer)
{
#region Search Criteria
this.SearchProperties[UITestControl.PropertyNames.ControlType] = "DataItem";
this.SearchProperties["HelpText"] = "MyCell's helptext property, this is correctly specified, but the HelpText is used only as a tooltip";
this.WindowTitles.Add("CodedUITestWindow");
#endregion
}
Thanks
I've normally seen ListView treated as a List, and the items as ListItem. You might want to use inspect.exe or the UI Test Builder to look at the properties. You can try to manually code the control. Sorry for posting speculation as an answer. Too long to be a comment.
WpfWindow PopUpWindow = new WpfWindow();
PopUpWindow.SearchProperties[WpfWindow.PropertyNames.Name] = "Pop Up Window Name";
WpfList List = new WpfList(PopUpWindow);
List.SearchProperties[WpfList.PropertyNames.Name] = "List Name";
WpfListItem ItemToSelect = new WpfListItem(List);
ItemToSelect.SearchProperties[WpfListItem.PropertyNames.Name] = "List Item Name";
// Click button to activate pop up window
ItemToSelect.Select();
// Creating the controls.
WpfWindow mainWindow = new WpfWindow();
// Add search properties.
WpfTable table = new WpfTable(mainWindow);
// Add search properties
WpfRow row = new WpfRow(table);
// Add search properties.
WpfCell cell = new WpfCell(row);
// Add search properties.
// Just adding the table and row as containers.
row.Container = table;
cell.Container = row;
}

WPF: Convert Datagrid/DataTable to Table for printing

Im trying to 'print' the contents of my datagrid / datatable.
I read something about converting DATAGRID To TABLE To FLOWDOCUMENT but I can't find a source how to do it.
I just need some sample codes on how to convert datagrid/dataTable to Table .
then I will just apply this solution : Printing a WPF FlowDocument
any idea?
Thanks and Sorry about for my noob question.
As far as my research went when I printed something I found that converting UI elements to pages is a wrong thing to attempt. Printing is a lot different then creating UI and there are no scrolls or draggable columns on paper :) so your data for printing will differ form data displayed on your forms.
As far as DataTable goes this is only an representation of data so you can easily produce a table that can be printed it already has rows and columns so it should be straight forward to begin: (note code not tested)
System.Data.DataTable dataTable = GetDataTable();
var table = new Table();
var rowGroup = new TableRowGroup();
table.RowGroups.Add(rowGroup);
var header = new TableRow();
rowGroup.Rows.Add(header);
foreach (DataColumn column in dataTable.Columns)
{
var tableColumn = new TableColumn();
//configure width and such
table.Columns.Add(tableColumn);
var cell = new TableCell(new Paragraph(new Run("column Header")));
header.Cells.Add(cell);
}
foreach (DataRow row in dataTable.Rows)
{
var tableRow = new TableRow();
rowGroup.Rows.Add(tableRow);
foreach (DataColumn column in dataTable.Columns)
{
var value = row[column].ToString();//mayby some formatting is in order
var cell = new TableCell(new Paragraph(new Run(value)));
tableRow.Cells.Add(cell);
}
}
//and print your table
If you ask me I find this API a little bit verbose but for complex documents with proper understanding it is very powerful.

DataGridViewComboBoxColumn setting selected index

I just cant get this to work.
I have a datagridview in winforms and in this one of my columns is a DataGridViewComboBoxColumn.
In my constructor I set it up like so
DataGridViewComboBoxColumn column = (DataGridViewComboBoxColumn)RectangleGrid.Columns["Material"];
DataTable data = new DataTable();
data.Columns.Add(new DataColumn("Value", typeof(int)));
data.Columns.Add(new DataColumn("Description", typeof(string)));
foreach (Materials M in DataStructure.Active.Active_Materials)
{
data.Rows.Add(M.MaterialNr, (M.MaterialNr + 1).ToString() + " " + M.Material.Name);
}
column.DataSource = data;
column.ValueMember = "Value";
column.DisplayMember = "Description";
And it actually works well except that nothing is selected in the drop down box which I want. I have googled this and for instance tried this approach: http://goo.gl/kBy8W but with no go because EditingControlShowing only happens when i click the box and not when it first comes up (so I can set selected index once it's clicked but thats no good).
The CellFormatting version at least changes the value but it just puts a string there rather than my first index from my data source.
I also tried this
column.DefaultCellStyle.NullValue = data.Rows[0]["Description"];
column.DefaultCellStyle.DataSourceNullValue = data.Rows[0]["Value"];
and that seemed to work but then when i selected the first index in the dropdown (so drop the dropdown down and then select the first index and then deselct the cell) I got an error from ParseFormattedValue where it says it cannot convert "value" to system.String.
There was this which seemed to be on the right track but i could not get it to work: http://goo.gl/VevA3
I ended up "solving" it in a very dirty solution that I don't like but it sort of works.
I had my datagridview bound to a datatable (not database) so what i did was i connected an event handler to the TableNewRow event in the datatable.
then i did this in that event handler
private void NewRectangleInserted(Object sender, DataTableNewRowEventArgs e)
{
if (e.Row[0].ToString() == "")
{
e.Row[0] = 0;
}
}
So basically when a new row is created I set the value of the combobox to 0 unless the user created the row by adding a value in that particular cell (why i check if it equals "")
The result is that as soon as you highlight a new line or any cell in a line the combobox is filled in. however the new line at the botton still has a blank combobox until you highlight it.
not perfect but a lot better. to bad it had to be done with a hack!

Updating of BindingSource in WinForms

During my attempts to use DataBinding in Winforms I've encountered with a problem. It looks like after updating of DataSource DataGridView doesn't refresh the data. Can't understand where is a problem.
var companies = new List<Company> { new Company { Name = "Test", Id = 100 }}
And here is the code for binding of items list to DataGridView:
bindingSource1.DataSource = _context.Companies;
dataGridView1.DataSource = bindingSource1.DataSource;
But after that if I update companies list like this
companies.Add(new Company { Name = "MDG", Id = 500 });
I can't find the newly added item into the DataGridView. Could someone help me to understand what I'm missing?
The problem here is that there is no way the BindingSource and the DataGridView can be made aware of changes to a List automatically.
Instead, use a new BindingList(). This has events that will be called to notify the BindingSource, and in turn the DataGridView that a new item to the list has been added.
var companies = new BindingList<Company>();
companies.Add(new Company { Name = "Test", Id = 100 });

How Do I get a Bindingsource to see a record added with the TableAdapter.Update() method without using .fill?

I have a large dataset that load in with a fill method on page load.
Then, a record can be added to the dataset.
All of that works fine, but the only way that I can get the bindingsource to recognize the new record is to do a fill method. This also works but is a perfomance problem. Why does the binding source not see the new record in the dataset?
Mainform Code. Works Great.
DialogResult returnFormVal;
Schedulers.DataSets.SchedOneFetch.WOMainFetchRow newRow = schedOneFetch.WOMainFetch.NewWOMainFetchRow();
Schedulers.Forms.NewWorkOrder genReport = new Schedulers.Forms.NewWorkOrder(ref newRow);
Int32 picNumber;
returnFormVal = genReport.ShowDialog();
schedOneFetch.WOMainFetch.Rows.Add(newRow);
wOMainFetchBindingSource.EndEdit();
wOMainFetchTableAdapter.Adapter.Update(schedOneFetch.WOMainFetch);
Int32 passBackVal = newRow.DISID;
SubForm code. Also works great.
passBackRow.DISDueDate = monthCalendar1.SelectionStart;
passBackRow.DISID = 99999999;
if (ckbEqpt.Checked == true & lbProcNum.Items.Count > 0)
{
passBackRow.DISEquip = Convert.ToInt32(lbProcNum.SelectedValue.ToString());
}
else
{
passBackRow.DISEquip = 0;
}
passBackRow.DISLineNumber = Convert.ToInt32(lbLineName.SelectedValue.ToString());
passBackRow.DISManHours = Convert.ToInt32(nudEstTotTime.Value);
passBackRow.DISNumberAss = Convert.ToInt32(nudEstTM.Value);
passBackRow.DISOpenDate = DateTime.Now;
passBackRow.DISOriginator = userID.DBUserID;
passBackRow.DISRequestor = 0;
passBackRow.DISResponsible = Convert.ToInt32(lbRespons.SelectedValue.ToString());
passBackRow.DISType = Convert.ToInt32(lbType.SelectedValue.ToString());
passBackRow.DISWorkAccomp = "";
passBackRow.DISWorkRequired = rtbWorkReq.Text;
passBackRow.MLID = 0;
passBackRow.LIID = 0;
passBackVal = 0;
this.Close();
Return control to main form. The new record has been added to the database.
wOMainFetchBindingSource.Position = wOMainFetchBindingSource.Find("DISID", passBackVal);
DataRowView dtaRow = (DataRowView)wOMainFetchBindingSource.Current;
String woID = dtaRow["DISID"].ToString();
FAIL! The bindingsource wont find the the new record, returns a -1 on the find and defaults to the first record in the dataset.
If I put the .fill method in between the dialog and the main page then it all works fine, but takes a loooonnng time to do the fill... seven or eight seconds.
I guess my understanding of the binding source is disfunctional, I had assumed that if the underlying dataset was updated then the bindingsource would see it.
So, first if someone has a suggestion on how to refresh the binding source without the fill I would appreciate it, and if someone can explain why this works the way it does I might be able to find a workaround.
Thanks
My understanding of the Bindingsource was correct, it was seeing the new record added. The issue is that the Dataset gets its information from a view. The add new method only populates the fields in the base table. The other fields, the ones assembled by the View, arent populated until the tableadapter re-reads by using the fill method. I dont see a way around this other than filling each of the fields of the new record, big drawback is that whenever the view or any of the tables assembled in the view are changed you would have to make sure to change the code. I will instead reduce the number of records being loaded on each fill.

Resources