473,779 Members | 2,050 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

DataGridView with databound combobox

1) I have a DataGridView with edit capability.
But in some columns I want to limit the input with a DropDownList.
There is no inbuilt column for DropDownLists so I intended to add one myself.
I thought the TemplateField would be a good candidate so I added a
DropDownList in the EditItemTemplat e and a Literal in the ItemTemplate, but
then I was kind of lost ....
It would be convenient to use the DataGridView for all other fields but
maybe it will not work?

2) Is there a way to Format the value in the normal Show/Edit fields? I have
a date column that looks strange with all "extra time details".
Mar 15 '06 #1
9 13907
Hi Jakob,

1) For the dropdownlist within a GridView, you can add within the
EditItemTemplat e a dropdownlist that retrieves its values based on a
datasource object. The dropdownlist can be updated using the one-way
databinding (using Eval) but in order for it to update the datasource you
would have to write code while consuming the GridVeiw.RowUpd ating event. I
have a sample that implements this strategy albeit using a FormView. You may
look at its source code and adapt it for the GridView

http://www.webswapp.com/codesamples/...s/default.aspx

2) As for your second question, if you have a DataFormatStrin g applied to a
BoundField you can set the ApplyFormatInEd itMode to true.

http://msdn2.microsoft.com/en-us/lib...de(VS.80).aspx
--
HTH,
Phillip Williams
http://www.societopia.net
http://www.webswapp.com
"Jakob Lithner" wrote:
1) I have a DataGridView with edit capability.
But in some columns I want to limit the input with a DropDownList.
There is no inbuilt column for DropDownLists so I intended to add one myself.
I thought the TemplateField would be a good candidate so I added a
DropDownList in the EditItemTemplat e and a Literal in the ItemTemplate, but
then I was kind of lost ....
It would be convenient to use the DataGridView for all other fields but
maybe it will not work?

2) Is there a way to Format the value in the normal Show/Edit fields? I have
a date column that looks strange with all "extra time details".

Mar 15 '06 #2
1) Looks interesting. I will try to apply it to my application tomorrow.
2) Perfect!

Thanks!
Mar 15 '06 #3
It is a bit different when using a GridView .....
This is what I came up with:

<asp:GridView ID="grdActivity " runat="server"
AutoGenerateCol umns="False" DataSourceID="o bjActivities">
<Columns>
<asp:BoundFie ld DataField="Acti vityDate"
HeaderText="Act ivityDate"/>
<asp:TemplateFi eld HeaderText="Act ivityTime">
<EditItemTempla te>
<asp:DropDownLi st ID="cboActivity Time"
runat="server"> </asp:DropDownLis t>
</EditItemTemplat e>
<ItemTemplate >
<asp:Literal ID="litActivity Time"
runat="server"> </asp:Literal>
</ItemTemplate>
</asp:TemplateFie ld>
<asp:CommandFie ld ShowDeleteButto n="True"
ShowEditButton= "True" />
</Columns>
</asp:GridView>

Protected Sub grdActivity_Row Editing(ByVal sender As Object, ByVal e As
System.Web.UI.W ebControls.Grid ViewEditEventAr gs) Handles
grdActivity.Row Editing

'Get hold of combobox
Dim row As GridViewRow = DirectCast(send er,
GridView).Rows( e.NewEditIndex)
Dim cbo As DropDownList =
DirectCast(row. FindControl("cb oActivityTime") , DropDownList)

'Load the combobox
cbo.DataSource = GetAvailableTim es.DefaultView
cbo.DataValueFi eld = "Time"
cbo.DataTextFie ld = "TimeString "
cbo.DataBind()
End Sub

Protected Sub grdActivity_Row Updating(ByVal sender As Object, ByVal e As
System.Web.UI.W ebControls.Grid ViewUpdateEvent Args) Handles
grdActivity.Row Updating

'Get hold of combobox
Dim row As GridViewRow = DirectCast(send er,
GridView).Rows( e.NewEditIndex)
Dim cbo As DropDownList =
DirectCast(row. FindControl("cb oActivityTime") , DropDownList)

'Set the New value of the object
e.NewValues("Ac tivityTime") = cbo.SelectedVal ue

'Accept the value
e.Cancel = False
End Sub
The first problem is that the FindControl will not find the DropDownList,
probably because it is placed inside a TemplateField.

Mar 16 '06 #4
Hi Jakob,

I figured that the best response is to put a sample of the GridView similar
the FormView that I had.
http://www.webswapp.com/codesamples/.../gridview.aspx

--
HTH,
Phillip Williams
http://www.societopia.net
http://www.webswapp.com
"Jakob Lithner" wrote:
It is a bit different when using a GridView .....
This is what I came up with:

<asp:GridView ID="grdActivity " runat="server"
AutoGenerateCol umns="False" DataSourceID="o bjActivities">
<Columns>
<asp:BoundFie ld DataField="Acti vityDate"
HeaderText="Act ivityDate"/>
<asp:TemplateFi eld HeaderText="Act ivityTime">
<EditItemTempla te>
<asp:DropDownLi st ID="cboActivity Time"
runat="server"> </asp:DropDownLis t>
</EditItemTemplat e>
<ItemTemplate >
<asp:Literal ID="litActivity Time"
runat="server"> </asp:Literal>
</ItemTemplate>
</asp:TemplateFie ld>
<asp:CommandFie ld ShowDeleteButto n="True"
ShowEditButton= "True" />
</Columns>
</asp:GridView>

Protected Sub grdActivity_Row Editing(ByVal sender As Object, ByVal e As
System.Web.UI.W ebControls.Grid ViewEditEventAr gs) Handles
grdActivity.Row Editing

'Get hold of combobox
Dim row As GridViewRow = DirectCast(send er,
GridView).Rows( e.NewEditIndex)
Dim cbo As DropDownList =
DirectCast(row. FindControl("cb oActivityTime") , DropDownList)

'Load the combobox
cbo.DataSource = GetAvailableTim es.DefaultView
cbo.DataValueFi eld = "Time"
cbo.DataTextFie ld = "TimeString "
cbo.DataBind()
End Sub

Protected Sub grdActivity_Row Updating(ByVal sender As Object, ByVal e As
System.Web.UI.W ebControls.Grid ViewUpdateEvent Args) Handles
grdActivity.Row Updating

'Get hold of combobox
Dim row As GridViewRow = DirectCast(send er,
GridView).Rows( e.NewEditIndex)
Dim cbo As DropDownList =
DirectCast(row. FindControl("cb oActivityTime") , DropDownList)

'Set the New value of the object
e.NewValues("Ac tivityTime") = cbo.SelectedVal ue

'Accept the value
e.Cancel = False
End Sub
The first problem is that the FindControl will not find the DropDownList,
probably because it is placed inside a TemplateField.

Mar 20 '06 #5
Thanks Phillip, I appreciate your effort!

1) I tried hard to get this working but one remaining stumblingblock is this
line:

<asp:DropDownLi st ID="cboActivity Time" runat="server"
DataSourceID="o bjTimes" DataValueField= "TimeShow" DataTextField=" TimeShow"
SelectedValue=' <%# Bind("ActivityT ime") %>' ></asp:DropDownLis t>

It will cause this error:
"'cboActivityTi me' has a SelectedValue which is invalid because it does not
exist in the list of items.
Parameter name: value"

Possible workaoround?
Your solution obviously works. What is the difference? My ObjectDatasourc e
retrieves a DataView, will that be a problem?
2) And I am still VERY eager to manipulate the DropDownList in code behind
(Load, set SelectedValue, etc). I am much more used to plain code than these
ObjectSource objects, and find it more flexible.

In the GridView RowEditing Event I can easily get hold of the Literal
control of the TemplateField. Is it impossible to get hold of the
DropDownList control in a similar way?

<asp:TemplateFi eld HeaderText="Act ivityTime">
<ItemTemplate >
<asp:Literal ID="litActivity Time" runat="server"
Text='<%# Eval("ActivityT ime") %>'></asp:Literal>
</ItemTemplate>
<EditItemTempla te>
<asp:ObjectData Source ID="objTimes" runat="server"
TypeName="SKF.B usinessLogic.St aticInfo"
SelectMethod="G etNormalTimes"
DataObjectTypeN ame="SKF.Busine ssLogic.StaticI nfo"></asp:ObjectDataS ource>
<asp:DropDownLi st ID="cboActivity Time" runat="server"
DataSourceID="o bjTimes" DataValueField= "TimeShow" DataTextField=" TimeShow"
SelectedValue=' <%# Bind("ActivityT ime") %>' ></asp:DropDownLis t>
</EditItemTemplat e>
</asp:TemplateFie ld>
Protected Sub grdActivity_Row Editing(ByVal sender As Object, ByVal e As
System.Web.UI.W ebControls.Grid ViewEditEventAr gs) Handles
grdActivity.Row Editing
Dim grd As GridView
Dim row As GridViewRow
Dim lit As New Literal
Dim cbo As DropDownList

grd = DirectCast(send er, GridView)
row = DirectCast(send er, GridView).Rows( e.NewEditIndex)
lit = DirectCast(row. FindControl("li tActivityTime") , Literal)
'cbo = DirectCast(row. FindControl("cb oActivityTime") , DropDownList)
End Sub
Mar 23 '06 #6
Hello Jakob,

Since you are using Bind (which will set the selected value from the data as
well as save the selected value to data upon update), the dropdownlist must
be populated with all possible values. In your specific code, for example,
if you had a value in the field named “ActivityTime ” that is not within the
set of values for “TimeShow” then you would get that error. It can also
happen if your datatable schema was created to allow nulls in ActivityTime.

The solutions are:
1- if the problem is happening due to Null values in AcitvityTime then you
can declare the dropdownlist like this:

<asp:DropDownLi st ID="cboActivity Time" runat="server"
AppendDataBound Items=”true
DataSourceID="o bjTimes" DataValueField= "TimeShow" DataTextField=" TimeShow"
SelectedValue=' <%# Bind("ActivityT ime") %>' ></asp:DropDownLis t>

http://msdn2.microsoft.com/en-us/lib...ms(VS.80).aspx

2- if the problem is happening due to illegal values saved in “ActivityTime ”
(that are not part of the set of values for TimeShow) then you can:

a. fix the data

b. create a UNION query within the objTimes that would bring not only the
values from the “TimeShow” but also any values in “ActivityTime ” that is not
included

c. handle it on the level of the user interface like I did on my sample
where I removed the Bind statement from the DropDownList and replaced with
code within the dropdownlist.Da taBound event, e.g.

Protected Sub cboAcitvityTime _DataBound(ByVa l sender As Object, ByVal e As
EventArgs)
Dim ddl As DropDownList = CType(sender, DropDownList)
Dim gvr As GridViewRow = CType(ddl.Namin gContainer, GridViewRow)
If Not gvr.DataItem Is Nothing Then
Dim strTimeShow As String = CType(gvr.DataI tem, DataRowView)("
TimeShow")
'be careful of the possibility that the value saved on the
'database does not exist in the valid selections that are
displayed
'on the list
ddl.ClearSelect ion()
Dim li As ListItem = ddl.Items.FindB yValue(strTimeS how)
If Not li Is Nothing Then li.Selected = True
End If

In which case you would also have to save the selected value upon update by
consuming the GridViewRowUpda ting, like this:

Protected Sub grdActivity_Row Updating (ByVal sender As Object, ByVal e As
GridViewUpdateE ventArgs)
Dim strTimeShow As String = CType(CType(sen der,
GridViewRow).Fi ndControl("cboA ctivityTime"), DropDownList).S electedValue
e.NewValues("Ac tivityTime") = strTimeShow
e.Cancel = False
End Sub
Regarding your question on how to find the dropdownlist within the
GridViewRow while handling the RowEditing event…

The RowEditing event is raised when a row's Edit button is clicked, but
before the GridView control enters edit mode.
http://msdn2.microsoft.com/en-us/lib...ng(VS.80).aspx

Which means that during this event processing the dropdownlist has not yet
been rendered. You can find that dropdownlist after the edit is complete
and the user pressed on the update command which will trigger the RowUpdating
event.
--
HTH,
Phillip Williams
http://www.societopia.net
http://www.webswapp.com
"Jakob Lithner" wrote:
Thanks Phillip, I appreciate your effort!

1) I tried hard to get this working but one remaining stumblingblock is this
line:

<asp:DropDownLi st ID="cboActivity Time" runat="server"
DataSourceID="o bjTimes" DataValueField= "TimeShow" DataTextField=" TimeShow"
SelectedValue=' <%# Bind("ActivityT ime") %>' ></asp:DropDownLis t>

It will cause this error:
"'cboActivityTi me' has a SelectedValue which is invalid because it does not
exist in the list of items.
Parameter name: value"

Possible workaoround?
Your solution obviously works. What is the difference? My ObjectDatasourc e
retrieves a DataView, will that be a problem?
2) And I am still VERY eager to manipulate the DropDownList in code behind
(Load, set SelectedValue, etc). I am much more used to plain code than these
ObjectSource objects, and find it more flexible.

In the GridView RowEditing Event I can easily get hold of the Literal
control of the TemplateField. Is it impossible to get hold of the
DropDownList control in a similar way?

<asp:TemplateFi eld HeaderText="Act ivityTime">
<ItemTemplate >
<asp:Literal ID="litActivity Time" runat="server"
Text='<%# Eval("ActivityT ime") %>'></asp:Literal>
</ItemTemplate>
<EditItemTempla te>
<asp:ObjectData Source ID="objTimes" runat="server"
TypeName="SKF.B usinessLogic.St aticInfo"
SelectMethod="G etNormalTimes"
DataObjectTypeN ame="SKF.Busine ssLogic.StaticI nfo"></asp:ObjectDataS ource>
<asp:DropDownLi st ID="cboActivity Time" runat="server"
DataSourceID="o bjTimes" DataValueField= "TimeShow" DataTextField=" TimeShow"
SelectedValue=' <%# Bind("ActivityT ime") %>' ></asp:DropDownLis t>
</EditItemTemplat e>
</asp:TemplateFie ld>
Protected Sub grdActivity_Row Editing(ByVal sender As Object, ByVal e As
System.Web.UI.W ebControls.Grid ViewEditEventAr gs) Handles
grdActivity.Row Editing
Dim grd As GridView
Dim row As GridViewRow
Dim lit As New Literal
Dim cbo As DropDownList

grd = DirectCast(send er, GridView)
row = DirectCast(send er, GridView).Rows( e.NewEditIndex)
lit = DirectCast(row. FindControl("li tActivityTime") , Literal)
'cbo = DirectCast(row. FindControl("cb oActivityTime") , DropDownList)
End Sub

Mar 24 '06 #7
Sorry I didn't answer before, but for some reason I was not notified of your
reply.

I am ashamed to tell you but I found out today(!) that all the problem was
caused by a totally different reason: the combobox was loaded with times of
the format "11.00" but the database contained times formatted as "11:00", and
I didn't notice!!!

As for combobox not being reachable in the RowEditing event, it makes sense :)

It all works by now and I am happy, Thanks!

Apr 1 '06 #8
Sorry I didn't answer before, but for some reason I was not notified of your
reply and didn't see it until today.

I am ashamed to confess that the main problem had a totally different
reason: the combobox was loaded with values on the form "11.00" but the
database held values on the form "11:00" and I was totally blind for the
difference all the time ... !

I understand that the combobox is not created yet in the RowEditing event,
it makes sense :)

It all works by now so I am all happy again, Thanks!

Apr 1 '06 #9
Thanks Jakob for the feed-back. I am glad you managed to get the
dropdownlist/gridview working.
--
Phillip Williams
http://www.societopia.net
http://www.webswapp.com
"Jakob Lithner" wrote:
Sorry I didn't answer before, but for some reason I was not notified of your
reply and didn't see it until today.

I am ashamed to confess that the main problem had a totally different
reason: the combobox was loaded with values on the form "11.00" but the
database held values on the form "11:00" and I was totally blind for the
difference all the time ... !

I understand that the combobox is not created yet in the RowEditing event,
it makes sense :)

It all works by now so I am all happy again, Thanks!

Apr 2 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
17244
by: Bob | last post by:
Thinking two things, 1- Creating a userControl -yeah you guessed it, a multi column drop down combobox - I've looked at several articles and did not find what I need, one that's bindable and that I can use in a datagrid view. 2- Extending the datagridview so that it can be added to the list in the column types when editing columns in the datagridview. I'm really getting PO'd at Microsoft for not including a multi column combobox both a...
0
1229
by: GregMandel | last post by:
Hi, I have a problem with the DatagridView of VB 2005. In a DatagridView I have a databound DataGridViewComboBoxColumn. My problem is now, that if I click in the header of this column, VB sorts the grid on the ValueMember (which is a non-significant ID number) and not on the DisplayMember (which is a significant text). This is for the user very confusing, because he sees a list that is not
8
26438
by: | last post by:
I am sure this has been asked and answered, but here goes anyway... VS.Net 2005, VB.Net How can you display more than one field in the displaymember property of a combobox inside the datagridview control? I am at a loss. Thanks, David
3
94267
by: sklett | last post by:
I'm changing from a DataGrid to a DataGridView and have run across a problem. The items that are bound to the DataGrid have an int Property that represents a primary key of a lookup table in my database. For example: table JobTypes 1 | Manager 2 | Controller 3 | Supervisor table Employee
8
11533
by: Brian Pelton | last post by:
This is on .Net 2.0 in a WinForms application. I have a DataGridView that is bound to a BindingSource. The DataGridView has 3 columns. The first two are "normal" text columns and the last is a combo box column. Data binding is working fine for the first two columns. I am able to edit values and persist them back to the bound object and ultimately back to the database.
4
39764
by: =?Utf-8?B?Q2hyaXM=?= | last post by:
how do you insert a new row to a databound datagridview? It won't allow this action.
3
6331
by: =?Utf-8?B?Sm9obiBCdW5keQ==?= | last post by:
New to databinding in vs2005, I always did it manually in 2003. I have no problem loading comboboxes, and a change in that combobox changes the data in the textboxes but I can not figure out a way to get the data in a datagridview to change. For example 2 columns are ID and amount_paid, the datagridview loads on form load with all ID's and amounts. How do I get it to only bring back the selected ID. Sounds like I may need to change the SQL...
1
7429
by: sklett | last post by:
I've got a strange situation here. I have a databound DataGridView that also has un-bound columns. When the view loads, I want to update the values of the unbound columns. If I attempt to modify the unbound column's cells in the OnLoad() handler the results are very strange. If I add a button to my view and update the unbound cells in the butt's handler it works fine. Here is an example of the code I'm trying to use (it's test code):...
18
6064
by: Andrus | last post by:
Marc, Thank you very much. I have issue on implementing add row properly using this. User presses down arrow in last row in grid starting adding new row. Then user changes its mind desiding that new row should not added and presses up arrow. DataGridView does not show this unfinished row anymore.
0
9474
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10305
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10137
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10074
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9928
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8959
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6724
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2867
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.