databinding >> Binding multiple checkboxes to a single data field

by Jeronimo Bertran » Wed, 20 Apr 2005 14:17:59 GMT

I have a form that uses databinding to update a database table. One of the
fields in the table corresponds to multiple checkbox controls in the form
(Flags Attributes). How can I perform the databinding in this case?

Thanks,

Jeronimo Bertran

databinding >> RE: Binding multiple checkboxes to a single data field

by v-jetan » Wed, 20 Apr 2005 17:19:24 GMT


Hi Jeronimo,

Thanks for your post!!

For checkboxes, we should use simple databinding to bind to the DataTable.
To do simple databinding, we can use CheckBox.DataBindings property, with
this property, we can associate multi-checkboxes' Checked property with the
bool column in the underlying datatable. Sample code lists below:
private void Form1_Load(object sender, System.EventArgs e)
{
this.checkBox1.DataBindings.Add("Checked", dt, "boolcolumn");
this.checkBox2.DataBindings.Add("Checked", dt, "boolcolumn");
}
Once these checkboxes have the same datasource, its checked state will keep
synchronized each other.(That is if we unchecked one checkbox, then other
checkboxes will become unchecked either)

Hope this helps.
===============================================
Thank you for your patience and cooperation. If you have any questions or
concerns, please feel free to post it in the group. I am standing by to be
of assistance.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

databinding >> RE: Binding multiple checkboxes to a single data field

by Jeronimo Bertran » Thu, 21 Apr 2005 01:52:15 GMT

Hi Jeffrey,

I noticed that I didn't express the problem very clearly... the problem I
have is that the underlying field does not represent a single checkbox but
it represents multiple distinct checkboxes. It is in fact a Flags integer
value that is stored on the database... here is an example:


[FlagsAttribute]
public enum MyFlags
{
none = 0x00,
flag1 = 0x01,
flag2 = 0x02
};

public MyFlags flags;


flags = (MyFlags) Row.Flags;

checkBox1.Checked = ((flags & flag1) != MyFlags.none);
checkBox2.Checked = ((flags & flag2) != MyFlags.none);

Thanks again,

Jeronimo

databinding >> RE: Binding multiple checkboxes to a single data field

by Jeronimo Bertran » Thu, 21 Apr 2005 02:53:07 GMT

I figured out how to do part of the work:


I created a property for each flag in my form:

public bool Flag1
{
get { return (flags & Flags.flag1) != Flags.none;}
set
{
if (value)
flags |= Flags.flag1;
else
flags &= ~Flags.flag1;
}
}

I then added the databinding:

this.checkBox1.DataBindings.Add("Checked", this, "Flag1");


This will keep the variable flag in synch with the controls.... however I
am still missing the databinding from the flags variable to the dataset. I
should mention that I am relying on the RowChanging event to confirm with
the user if changes should be saved and simply updating the row with the
new flags value will not generate this event when I end the current edit.

Thanks again.

databinding >> RE: Binding multiple checkboxes to a single data field

by a2Fib3JrYQ » Thu, 21 Apr 2005 05:43:03 GMT

I use custom Format and Parse handlers to convert between the CheckBox bool
value and whatever is in the database. In the example below, the handlers
convert true/false to "Y"/"N". You can write your own handlers to mask the
checkbox values to the corresponding part of the database field. Sounds like
you'd need a different pair of handlers for each checkbox, all bound to the
same field. See help for Binding.Format and .Parse. I'm wondering if you
might get exceptions about multiple bindings to the same field. Hope this
helps!

-----------------------------------------------------------
// bind the checkbox value to the bool column
Binding b = new Binding(@"Checked", dsService.dataService,

dsService.dataService.IsUserRouteStrColumn.ColumnName);
// the binding needs a format handler to convert Y/N to bool, and a parse
handler to convert back
b.Format += new ConvertEventHandler(ConvertYesNoToBoolHandler);
b.Parse += new ConvertEventHandler(ConvertBoolToYesNoHandler);
chkRouteStr.DataBindings.Add(b);

databinding >> RE: Binding multiple checkboxes to a single data field

by v-jetan » Thu, 21 Apr 2005 16:04:37 GMT

Hi Jeronimo,

Yes, with your further good explaination I think I understand your scenario
and problem.

I think kaborka has pointed you the correct direction. For such simple
databinding, we can leverage Binding object's Parse and Format event to
hook into the binding process. In Binding.Format event, we can dynamically
get the underlying field's value through ConvertEventArgs.Value proerty and
apply your program logic to parse this value into Bool type. Also, once the
user changed checkbox's checked state at UI side, Binding.Parse event will
fire, then we can apply the reverse logic in this event to parse the
checked state into certain MyFlags type.

I have writen a little sample code snippet, which demostrate how to
implement Format event:

private void button1_Click(object sender, System.EventArgs e)
{
MyClass []obj=new MyClass[5];
for(int i=0;i<5;i++)
{
obj[i]=new MyClass();
obj[i].Flags=(MyFlags)(i%3);
}
Binding b1=new Binding("Checked", obj, "Flags");
b1.Format+=new ConvertEventHandler(b1_Format);

Binding b2=new Binding("Checked", obj, "Flags");
b2.Format+=new ConvertEventHandler(b2_Format);

this.checkBox1.DataBindings.Add(b1);
this.checkBox2.DataBindings.Add(b2);
}

private void b1_Format(object sender, ConvertEventArgs e)
{
if(e.DesiredType==typeof(bool))
{
e.Value=((((MyFlags)e.Value)&MyFlags.flag1) != MyFlags.none);
}
}

private void b2_Format(object sender, ConvertEventArgs e)
{
if(e.DesiredType==typeof(bool))
{
e.Value=((((MyFlags)e.Value)&MyFlags.flag2) != MyFlags.none);
}
}

private void button2_Click(object sender, System.EventArgs e)
{
this.checkBox1.DataBindings["Checked"].BindingManagerBase.Position=
(this.checkBox1.DataBindings["Checked"].BindingManagerBase.Position+1)%5;
}
The code in button2_Click just changes binding object position, then the UI
side checkbox state should change correspondingly.
It works well on my side. Thanks
=================================================================
Thank you for your patience and cooperation. If you have any questions or
concerns, please feel free to post it in the group. I am standing by to be
of assistance.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

databinding >> RE: Binding multiple checkboxes to a single data field

by Jeronimo Bertran » Fri, 22 Apr 2005 04:30:19 GMT

Thanks to both of you...

I will test it.

Jeronimo

databinding >> RE: Binding multiple checkboxes to a single data field

by v-jetan » Fri, 22 Apr 2005 10:14:25 GMT

Ok, please feel free to feedback your test result here. Thanks

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

Similar Threads

1. About binding checkboxes and multiple row fields modification - VB.Net

2. How to bind multiple data items to single control

Hi,

I have a Repeater control and want to bind a hyperlink to each repeated
row. For this I can use the following syntax (excuse any incorrect
naming but I don't have any code to hand):

<asp:Hyperlink id="x" NavigateToUrl='<%# Bind("id", "Page.aspc?id={0}")
%> Text="Text"></asp:Hyperlink>

This all works find but I'd like to be able to bind 2 data items such
as this:

<asp:Hyperlink id="x" NavigateToUrl='<%# Bind("id, name",
"Page.aspc?id={0}&name={1}") %> Text="Text"></asp:Hyperlink>

Obviously this doesn't work, but is there another way to do this?

Thanks

Nick

3. One Usercontrol Multiple Instance in a Single Page --Required Field Validator Problem - Asp.Net

4. Single Field Binding ASP.NET 2.0

Hey I've been looking everywhere and trying a few things but can't figure it
out.

Is there some documentation somewhere on how DataComponent's work?  Not the
SQL Data Source or Data Sources in general, but the actual DataComponent
where you can define queries (kinda reminds me of a dataset).  I want to do
simple queries (not multiple rows) and can't seem to bind it to a label
control

Any help would be appreciated.

Thanks,
CJ


5. Multiple fields in a single textbox - VB.Net

6. FormView checkbox two-way bind problem with null fields

Hi to all,

I think this question may already have been posted but I couldn't find
any post on this so I'm asking again.

I've a FormView bound to a SQLDataSource.
I've edited the EditItemTemplate placing some checkboxes bound to some
fields. I'm using Bind(FieldName) declarative syntax cause I need to
update these fields. In the source these fields my be empty (null).

When I switch to edit view I get the following error:

 Conversion from type 'DBNull' to type 'Boolean' is not valid.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Conversion from type
'DBNull' to type 'Boolean' is not valid.

Source Error:

Line 86:                 <asp:CheckBox ID="CheckBox1" runat="server"
Checked='<%# Bind("F01MINORI") %>' CssClass="radiolist"
Line 87:                     Style="z-index: 124; left: 124px;
position: absolute; top: 293px" Text="minore" />
Line 88:                 <asp:CheckBox ID="CheckBox2" runat="server"
Checked='<%# Bind("F01MINORIH") %>' CssClass="radiolist"


Source File: x:\xxx\xxxxxxx.aspx    Line: 86 

Now, the source of this error is pretty clear to me. The fields is
empty and conversion from DBNull object to boolean value can not
happen. My question is, being forced to use Bind(), how can I handle
empty fields (not only for checkboxes but for bound controls in
general)?

Is there another way to bind two-way controls?

Thanks in advance.

7. Problem binding multiple properties in one control to a single row - ADO.Net

8. controlling visibility of multiple controls bound to a single property

ok... weirdness... hoping someone can help... i have a list that does
all the stuff that i need to do to bind to it...  i want to bind the
visibility of one grid and two different buttons to my list.  the
problem is that although the format event gets called multiple times,
it is always the same control that gets passed as the sender.  that is,
i set a breakpoint at showControl and i hit the breakpoint four times,
but each time its the grid that is being passed as the sender...
anybody know why this would be the case?  my code is blow...

bnd = New Binding("Visible", myList, "ItemName")
bnd2 = New Binding("Visible", myList, "ItemName")
bnd3 = New Binding("Visible", myList, "ItemName")
AddHandler bnd.Format, AddressOf showControl
AddHandler bnd2.Format, AddressOf showControl
AddHandler bnd3.Format, AddressOf showControl
grd.DataBindings.Add(bnd)
btnScrollUp.DataBindings.Add(bnd2)
btnScrollDown.DataBindings.Add(bnd3)

Private Sub showControl(ByVal sender As Object, ByVal e As

System.Windows.Forms.ConvertEventArgs)
        Dim bnd As Binding = CType(sender, Binding)
        Dim theList As myList = bnd.DataSource

        e.Value = theList.hasItems
End Sub