Load dropdown with Database Data - sql

I'm new in windows forms and I have comboBox called cbTasks and I want to populate it in load window so I execute sql task as:
private void StatusForm_Load(object sender, EventArgs e)
{
var db = new SQLConnMgr();
var taskType = string.Format("SELECT [Name], [Id] FROM [TaskType] WHERE TaskTypeCategoryId = {0} ", TaskTypeCategoryId);
var taskList = db.GetTableBySQL(taskType);
}
As you can see I have items into taskList variable, but now I want to fill comboBox. How can I achieve that? I try to use foreach but I don't know how to call [Name] into Add method:
foreach(DataRow task in taskList.Rows)
{
cbTasks.Items.Add()
}
How can I achieve that? Regards

Just bind tghe datatable to the dropdown, the dot new framework does the looping for you behind the scenes:
cbTasks.DataSource = taskList;
cbTasks.DisplayMember = "Name";
cbTasks.ValueMember = "Id";

Related

FastObjectListView UpdateObject() randomly reorders rows within primary sort

Data is a generic List of domain objects.
I click the "Deploy Status" column header to sort on that column.
I have a button that does nothing more than folv.UpdateObject(someObject) .
Every time I press that button, the Deploy Status column maintains its sort, but all rows within the sorted blocks are randomly reordered, as per screenshot.
I have commented out everything in the form's code beyond loading the data, the test button, and the FastObjectListView's column.Add() and .SetObjects(). There are no event handlers wired up for the FastObjectListView. I am not setting PrimarySort or SecondarySort in code; only by clicking with the mouse.
You should be able to fix this problem by either calling Sort after your button's call to UpdateObject or changing your usage of UpdateObject to RefreshObject
Reproducing the problem (C# Repro for the issue in the API)
This seems to reproduce the problem you are having. Run the code, sort the Other column ascending. Click the update button.
public class MainForm : Form
{
public MainForm()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
//
// MainForm
//
this.ClientSize = new System.Drawing.Size(300, 300);
this.Name = "MainForm";
this.ResumeLayout(false);
this.PerformLayout();
var OLVa = new FastObjectListView();
OLVa.Width = 250;
OLVa.Height = 250;
OLVa.Columns.Add(new OLVColumn("ID", "ID"));
OLVa.Columns.Add(new OLVColumn("Other", "Other"));
var l1 = new lolz(1, 3);
OLVa.AddObject(l1);
OLVa.AddObject(new lolz(2,3));
this.Controls.Add(OLVa);
var btn = new Button()
{
Text = "Update",
Top = OLVa.Bottom
};
btn.Click += (s,e)=>OLVa.UpdateObject(l1);
this.Controls.Add(btn);
}
private class lolz
{
public int ID;
public int Other;
public lolz(int id, int other)
{
ID = id;
Other = other;
}
}
}
Fixing the problem
The following would fix it for the above example:
btn.Click += (s,e)=>
{
OLVa.BeginUpdate();
try
{
OLVa.UpdateObject(l1);
OLVa.Sort();
}
finally
{
OLVa.EndUpdate();
}
};

pass a variable to the result of an asynchronous call method's

There is a DataGrid with data in the Net 4.0 App. For the selected row, I get the value of one of the columns and pass it to the asynchronous method of the WCF service. Is it possible to pass this value as a result this method?
btn_Click(object sender, RoutedEventArgs e) {
DataRowView rv = (DataRowView)dgData.SelectedItem;
rv["TimeBeg"] = DateTime.Now.ToString("h:mm:ss");
string val=rv["Id"].ToString();
srAsync.ServClient clP = new srAsync.ServClient();
clP.MethodCompleted += cl_MethodComplete;
clP.MethodAsync(val);
}
After the call, the user can select another DataGrid Item, and call Async method for them, but in complete method I need to call another method with this value and update the rows DataGrid
private void cl_MethodComplete(object sender, srA.MethodCompletedEventArgs e) {
rv["TimeEnd"] = DateTime.Now.ToString("h:mm:ss");
sr.ServClient clP = new sr.ServClient();
clP.AnotherMethod(val);
...
What I would do is passing the row the user clicks on to the handler, using a lambda function:
btn_Click(object sender, RoutedEventArgs e) {
DataRowView rv = (DataRowView)dgData.SelectedItem;
rv["TimeBeg"] = DateTime.Now.ToString("h:mm:ss");
string val = rv["Id"].ToString();
srAsync.ServClient clP = new srAsync.ServClient();
clP.MethodCompleted += (currentSender, currentE) => cl_MethodComplete(currentSender, currentE, rv);
clP.MethodAsync(val);
}
Of course you will have to add another parameter to cl_MethodComplete, which will be able to work on the original row:
private void cl_MethodComplete(object sender, srA.MethodCompletedEventArgs e, DataRowView originalRow) {
originalRow["TimeEnd"] = DateTime.Now.ToString("h:mm:ss");
sr.ServClient clP = new sr.ServClient();
clP.AnotherMethod(val);
...

Pass ROWID in ListView to new Activity when clicked

Very new to programming here. I am working on an android application that allows the user to create and manage a database for food products that he has at home. Currently the SQL database allows you to create new database entries where each entry consists of a rowid, a product name, the amount you have of the product and finally an expiry date.
Then a ListView is populated with any existing data in the database and an OnItemClickListener for this ListView is setup to handle a click event so that if the user clicks on a row in the ListView he is send to a new edit activity. Here he can edit the name, the amount and the expiry date if needed.
Now I am trying to retrieve the data (name, amount, date) when a specific row is clicked to send it to the next activity and here's what I've got so far..
Setup a public cursor in the SQL database to get all KEYS for a specific rowid:
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_AMOUNT, KEY_DATE};
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = ourDatabase.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
Then in the activity with the ListView I have the following set up to launch the new edit activity:
private void listViewItemClick(){
ListView ourList = (ListView) findViewById(R.id.lvProducts);
ourList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Intent openProductsEdit = new Intent(Products.this,
ProductsEdit.class);
startActivity(openProductsEdit);
finish();
}
});
}
And finally I would like to set the EditTexts in my edit activity to the data passed on during the click event:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.products_edit);
initiate();
Intent getProductName = getIntent();
String productName = getProductName.getStringExtra("productName");
etName.setText(productName);
Intent getProductAmount = getIntent();
String productAmount = getProductAmount.getStringExtra("productAmount");
etAmount.setText(productName);
Intent getProductDate = getIntent();
String productDate = getProductDate.getStringExtra("productDate");
etDate.setText(productName);
I have been trying to retrieve the specific data for a clicked row through the cursor I have setup in the SQL database and then pass it on with openProductsEdit.putExtra in the onItemClick method, but I can't seem to successfully connect the two together.
Any suggestions on how to solve this would be greatly appreciated.
EDIT: I solved my problem by coding my onSetItemClickListener like this
private void listViewItemClick(){
final ListView ourList = (ListView) findViewById(R.id.lvProducts);
ourList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Cursor cursor = (Cursor) ourList.getItemAtPosition(position);
Intent openProductsEdit = new Intent(Products.this,
ProductsEdit.class);
int rowid = cursor.getInt(0);
String name = cursor.getString(1);
String amount = cursor.getString(2);
String date = cursor.getString(3);
openProductsEdit.putExtra("rowid", rowid);
openProductsEdit.putExtra("name", name);
openProductsEdit.putExtra("amount", amount);
openProductsEdit.putExtra("date", date);
startActivity(openProductsEdit);
finish();
}
});
Here the cursor.getString(1) sets a string to the second column of the selected row (in this case a product name). This is then passed on to an edit activity where the data is put into corresponding EditTexts.
PROBLEM SOLVED! ;)

datagridview ,CurrentCellChanged,AllowUserToAddRows,textbox.keydown event

my question is why add a textbox controls to datagridview ,then press keyboard to add a blank row to datagridview . but i find the cursor always jump to above row's cell,not position where i press keyboard's cell.so i get confused .
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Visible = false;
textBox1.Width = 0;
dataGridView1.Controls.Add(textBoxenter code here1);
System.Data.DataTable dt = new DataTable();
dt.Columns.Add("Name");`enter code here`
dt.Columns.Add("Sex");
System.Data.DataRow dr;
for (int i = 0; i < 10; i++)
{
dr = dt.NewRow();
dr["Name"] = string.Format("Name{0}", i);
dr["Sex"] = string.Format("Sex{0}", i);
dt.Rows.Add(dr);
}
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = dt;
}
private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
this.textBox1.Visible = false;
this.textBox1.Width = 0;
try
{
if (dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].HeaderText == "Name")
{
this.textBox1.Left = dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, true).Left;`</i>`
this.textBox1.Top = dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, true).Top;`</i>`
this.textBox1.Width = dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, true).Width - 2;`</i>enter code here`
this.textBox1.Height = `</i>`dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex, dataGridView1.CurrentCell.RowIndex, true).Height - 2;
`</i>`
string str = Convert.ToString(this.dataGridView1.CurrentCell.Value); this.textBox1.Text = str;
this.textBox1.Visible = true;
}
}
catch
{
}
}
private void textBox1_Validating(object sender, CancelEventArgs e)
{
this.dataGridView1.CurrentCell.Value = this.textBox1.Text;
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1 .AllowUserToAddRows =true ;
}
}
}
Alright, against my better judgement I will provide an partial answer for this.
First off, this is not VB.NET, this is C#.
Secondly, I can't find any code that actually adds a row for you or indicates that you have tried it. So I will only answer the problem you state in your comment. This since it seems a bit to hard for you to grasp and I want to be helpful.
Which is: "The question is why i press a key in textbox, the cell position would be move to the above cell".
This happens when you have selected the new row with an asterix ( * ) as row number. This is called a "Manually added row".
So now when you try to add text from your textbox you select the last row and start typing in the textbox. What happends then is that the event KeyDown is fired and it executes this command:
this.dataGridView1.AllowUserToAddRows = false;
Which, to make things simple, means "Delete the row with the asterix ( * )". So now the last row no longer exist and the DataGridView needs a new selection. The selection is then passed to the row above. So now the second last row is the last row, and it will be selected. Then you execute this command:
this.dataGridView1 .AllowUserToAddRows =true;
Which means "Create the row with the asterix ( * )", thus making the last row appear again. However, the second last row selection is not affected by adding this row again. So it remains selected. This creates the endresult that the selection jumps up to the line above.

Silverlight 4 Overriding the DataForm Autogenerate to insert Combo Boxes bound to Converters

I've been working towards a solution for some time and could use a little help. I know I've seen an example of this before, but tonight I cannot find anything close to what I need.
I have a service that provides me all my DropDownLists, either from Cache or from the DomainService. They are presented as IEnumerable, and are requested from the a repository with GetLookup(LookupId).
I have created a custom attribute that I have decorated my MetaDataClass that looks something like this:
[Lookup(Lookup.Products)]
public Guid ProductId
I have created a custom Data Form that is set to AutoGenerateFields and I am intercepting the autogenerate fields.
I am checking for my CustomAttribute and that works.
Given this code in my CustomDataForm (standard comments removed for brevity), what is the next step to override the field generation and place a bound combobox in its place?
public class CustomDataForm : DataForm
{
private Dictionary<string, DataField> fields = new Dictionary<string, DataField>();
public Dictionary<string, DataField> Fields
{
get { return this.fields; }
}
protected override void OnAutoGeneratingField(DataFormAutoGeneratingFieldEventArgs e)
{
PropertyInfo propertyInfo = this.CurrentItem.GetType().GetProperty(e.PropertyName);
foreach (Attribute attribute in propertyInfo.GetCustomAttributes(true))
{
LookupFieldAttribute lookupFieldAttribute = attribute as LookupFieldAttribute;
if (lookupFieldAttribute != null)
{
// Create a combo box.
// Bind it to my Lookup IEnumerable
// Set the selected item to my Field's Value
// Set the binding two way
}
}
this.fields[e.PropertyName] = e.Field;
base.OnAutoGeneratingField(e);
}
}
Any cited working examples for SL4/VS2010 would be appreciated.
Thanks
Update - Here's where I am at. I get my combo now, but it's always empty even though itemsSource is not.
if (lookupFieldAttribute != null)
{
ComboBox comboBox = new ComboBox();
Binding newBinding = e.Field.Content.GetBindingExpression(TextBox.TextProperty).ParentBinding.CreateCopy();
newBinding.Mode = BindingMode.TwoWay;
newBinding.Converter = new LookupConverter(lookupRepository);
newBinding.ConverterParameter = lookupFieldAttribute.Lookup.ToString();
comboBox.SetBinding(ComboBox.SelectedItemProperty,newBinding);
comboBox.ItemsSource = lookupRepository.GetLookup(lookupFieldAttribute.Lookup);
e.Field.Content = comboBox;
}
I found a solution.
if (lookupFieldAttribute != null)
{
ComboBox comboBox = new ComboBox();
Binding newBinding = e.Field.Content.GetBindingExpression(TextBox.TextProperty).ParentBinding.CreateCopy();
var itemsSource = lookupRepository.GetLookup(lookupFieldAttribute.Lookup);
var itemsSourceBinding = new Binding { Source = itemsSource };
comboBox.SetBinding(ItemsControl.ItemsSourceProperty, itemsSourceBinding);
newBinding.Mode = BindingMode.TwoWay;
newBinding.Converter = new LookupConverter(lookupRepository);
newBinding.ConverterParameter = lookupFieldAttribute.Lookup.ToString();
comboBox.SetBinding(ComboBox.SelectedItemProperty,newBinding);
e.Field.Content = comboBox;
}