Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Windows Forms / WinForm Data Binding / October 2006

Tip: Looking for answers? Try searching our database.

bound combobox default value

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Chuck P - 20 Oct 2006 15:36 GMT
I have a combobox (DropDownList style) that I filled with objects that have
two properites Display and Value.

The combobox is bound to a binding source
this.cbxStaff.DataBindings.Add("SelectedValue", this.intakesBindingSource,
"StaffID");

In the form load I have
ComboBox_Load<int>(cbxStaff, "Name_Zno", "StaffID", (new
Wits.dsLookUpTableAdapters.lutSpecialistsTableAdapter()).GetData(IsActiveOnly), UsePickOne, -1);
  intakesBindingSource.AddNew();
  cbxStaff.SelectedIndex = 1;

When the form displays the SeletedIndex is -1.
How can I set the SelectedIndex to 1.

      public static void ComboBox_Load<T>(ComboBox comboBox, string
displayColumnName, string valueColumnName, DataTable dataTable, string
FirstMemberToDisplay, T FirstValueToUse)
       {
           List<DisplayValueItem<T>> myList = new
List<DisplayValueItem<T>>();

           if (!string.IsNullOrEmpty(FirstMemberToDisplay))
               myList.Add(new DisplayValueItem<T>(FirstValueToUse,
FirstMemberToDisplay));

           int iRowCount = dataTable.Rows.Count;
           for (int i = 0; i < iRowCount; i++)
               myList.Add(new
DisplayValueItem<T>((T)dataTable.Rows[i][valueColumnName],
dataTable.Rows[i][displayColumnName].ToString()));

           comboBox.DisplayMember = "Display";
           comboBox.ValueMember = "Value";
           comboBox.DataSource = myList;
       }

  public struct  DisplayValueItem<T>
       {
           private T mValue;
           private string mDisplay;
           public DisplayValueItem(T ValueField, string DisplayField)
           {
               mValue = ValueField;
               mDisplay = DisplayField;
           }
           public T Value
           {
               get { return mValue; }
           }

           public string Display
           {
               get { return mDisplay; }
           }

           public override bool Equals(object obj)
           {
               if ((obj != null) && (obj.GetType() == this.GetType()))
               {
                   DisplayValueItem<T> objToCompare =
(DisplayValueItem<T>)obj ;
                   return mValue.Equals(objToCompare.mValue) &&
mDisplay.Equals(objToCompare.mDisplay);
               }
               else
                   return false;
           }

           public override int GetHashCode()
           {
               return mDisplay.GetHashCode() ^ mValue.GetHashCode();
           }    

       }
Bart Mermuys - 20 Oct 2006 20:36 GMT
Hi,

>I have a combobox (DropDownList style) that I filled with objects that have
> two properites Display and Value.
>
> The combobox is bound to a binding source
> this.cbxStaff.DataBindings.Add("SelectedValue", this.intakesBindingSource,
> "StaffID");

What's the datasource for intakesBindingSource ?  A DataSet/DataTable ?  If
so, then the best thing to do would be to set the default value to -1 for
the StaffID column, considering that your special top level item has -1 as a
value.

> In the form load I have
> ComboBox_Load<int>(cbxStaff, "Name_Zno", "StaffID", (new
[quoted text clipped - 5 lines]
> When the form displays the SeletedIndex is -1.
> How can I set the SelectedIndex to 1.

I assume you meant setting SelectedIndex to 0 (the first item).

HTH,
Greetings

>       public static void ComboBox_Load<T>(ComboBox comboBox, string
> displayColumnName, string valueColumnName, DataTable dataTable, string
[quoted text clipped - 56 lines]
>
>        }
Chuck P - 20 Oct 2006 21:28 GMT
thanks it worked,

Odd that if I do    DateTimePicker.Value = now();
It gets stuffed in to the dataset but doing combox.selected index = 0 does
not.
Bart Mermuys - 20 Oct 2006 22:01 GMT
Hi,

> thanks it worked,
>
> Odd that if I do    DateTimePicker.Value = now();
> It gets stuffed in to the dataset but doing combox.selected index = 0 does
> not.

By default before any value is pushed to the DataSource, the property
changed event (if any) and then the control validate event needs to be
fired.

I've tried a similar setup as yours and i don't see the difference (the
first item is selected).

Nevertheless i would use the default value and try to avoid changing
Controls that are bound. You can also handle DataTable.TableNewRow event to
set a default value as DateTime.Now.

hth,
Greetings
Linda Liu [MSFT] - 23 Oct 2006 06:54 GMT
Hi Chuck,

As for setting default value for a bound combobox when you add a new row
into a datatable, you have two options to do it.

One option is to set the DefaultValue property of data column of the
datatable to a specific value,e.g. -1. To do this, open the datatable in
the designer, select the data column of the datatable and set the
DefaultValue property of the data column in the Properties window.

The other option is to handle the DataNewRow event of the datatable to set
the 'default' values of the data columns for the new row. The following is
a sample.

public Form1()
{
this.dataSet1.DataTable1.TableNewRow += new  
DataTableNewRowEventHandler(DataTable1_TableNewRow);
}

void DataTable1_TableNewRow(object sender, DataTableNewRowEventArgs e)
{
  e.Row[1] = -1;                                  // this column is of
type int and bound to a combobox
  e.Row[2] = DateTime.Now;        // this column is of type DateTime and
bound to a datetimepicker
}

> Odd that if I do    DateTimePicker.Value = now();
>It gets stuffed in to the dataset but doing combox.selected index = 0 does
not.

I performed a test but I didn't reproduce the above problem you described.
I bound a datetimepicker control to a data column of a datatable and set
the Value property of the datetimepicker after I add a new row into the
data source. The code is as follows.

// this.bindingSource1.DataSource is the datatable
this.bindingSource1.AddNew();

dateTimePicker1.Value = DateTime.Now

// assume the index of the new row is 1 and the index of the DateTime
column is 2
//  the value variable returns an empty string
string value = ((DataRowView)this.bindingSource1[1])[2].ToString();  

In fact, after we set the value of the bound control programmatically, the
new value is not stuffed into the data source. We should call
BindingSource.EndEdit method to apply the pending changes to the underlying
data source. The following is a sample.

this.bindingSource1.AddNew();
dateTimePicker1.Value = DateTime.Now
this.bindingSource1.EndEdit();
// the value variable returns the current datetime
string value = ((DataRowView)this.bindingSource1[1])[2].ToString();  

Hope this helps.
If you have anything unclear, please feel free to let me know.

Sincerely,
Linda Liu
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.