Getting the selected value from an embedded DropDownList in GridView's ItemTemplate when Updating

Hi all,

 I wrote about this problem but none could help me so I'm posting it again with hope someone help me to solve this problem.

OK. I have a GridView(ProductsGridView) bound to an ObjectDataSourceObject. One of the Columns is with DDL, which takes the CategoryID from the Product. The problem comes when I start to Edit the Row, it goes to edit mode, I change the Category for example, and then when I hit the Update button the value from the DDL is not Updated. It still has the value which it has at first.

How can I get the Updated value and give it to my Business Object(Product)? The method for updating the product is:

public void Update(Product aProduct)

{...} 

which takes the Updated product and puts it in the DataBase. 

Thanks to all of you. 

<!-- PRODUCTS GRID VIEW -->
                    <asp:GridView ID="ProductsGridView" runat="server" AllowPaging="True" AutoGenerateColumns="False"
                        BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" CellPadding="4" DataSourceID="ProductDatSource"
                        ForeColor="#333333" GridLines="Vertical" Height="168px" EmptyDataText="Няма записани продукти"
                        OnRowUpdating="ProductsGridView_RowUpdating" DataKeyNames="ID">
                        <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                        <RowStyle BackColor="#E3EAEB" BorderColor="Red" BorderStyle="Outset" BorderWidth="10px"
                            HorizontalAlign="Left" VerticalAlign="Middle" Wrap="True" />
                        <EditRowStyle BackColor="#7C6F57" BorderColor="Red" />
                        <SelectedRowStyle BackColor="#C5BBAF" BorderColor="Red" Font-Bold="True" ForeColor="#333333" />
                        <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
                        <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
                        <AlternatingRowStyle BackColor="White" />
                        <Columns>
                            <asp:CommandField ButtonType="Image" CancelImageUrl="~/Pictures/Icons/Cancel.png"
                                DeleteImageUrl="~/Pictures/Icons/Delete.png" EditImageUrl="~/Pictures/Icons/Edit.png"
                                ShowDeleteButton="True" ShowEditButton="True" UpdateImageUrl="~/Pictures/Icons/Update.png" />
                            <asp:TemplateField HeaderText="Категория">
                                <EditItemTemplate>
                                    <asp:DropDownList ID="dropdownlistCategory" runat="server" DataSourceID="ProductDatSource"
                                        DataTextField="CategoryName" DataValueField="CategoryID" SelectedValue='<%# Bind("CategoryID") %>'
                                        Width="139px">
                                    </asp:DropDownList>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:DropDownList ID="dropdownlistCategoryIT" runat="server" DataSourceID="ProductDatSource"
                                        DataTextField="CategoryName" DataValueField="CategoryID" SelectedValue='<%# Bind("CategoryID") %>'
                                        Width="133px">
                                    </asp:DropDownList>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" SortExpression="CategoryID" />
                            <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />
                            <asp:BoundField DataField="Size" HeaderText="Size" SortExpression="Size" />
                            <asp:BoundField DataField="Img1" HeaderText="Img1" SortExpression="Img1" />
                            <asp:BoundField DataField="Img3" HeaderText="Img3" SortExpression="Img3" />
                            <asp:BoundField DataField="Img2" HeaderText="Img2" SortExpression="Img2" />
                            <asp:BoundField DataField="MainImg" HeaderText="MainImg" SortExpression="MainImg" />
                            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                        </Columns>
                        <EmptyDataTemplate>
                            &nbsp;Няма записани продукти.
                        </EmptyDataTemplate>
                    </asp:GridView>
                    <asp:ObjectDataSource ID="ProductDatSource" runat="server" DataObjectTypeName="Product"
                        DeleteMethod="Delete" SelectMethod="GetAll" TypeName="ProductList" UpdateMethod="Update">
                        <UpdateParameters>
                            <asp:FormParameter Direction="InputOutput" FormField="CategoryID" Name="newparameter"
                                Type="String" />
                        </UpdateParameters>
                    </asp:ObjectDataSource>
 

0
dekartsoft
11/28/2007 7:06:47 AM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

14 Replies
1182 Views

Similar Articles

[PageSpeed] 37

Try this  

protected void ProductsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DropDownList dd1;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if(e.Row.RowState == DataControlRowState.Edit)
            {
                dd1 = (DropDownList)e.Row.FindControl("dropdownlistCategory");
                dd1.DataSource = UpdateCategories();
                dd1.DataTextField = "Category_ID";
                dd1.DataValueField = "CategoryName";
                dd1.DataBind();
            }
        }
    }


Regards,Vinz

"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
0
vinz
11/28/2007 7:57:06 AM

 Hi Distributor,

Thanks for the reply, but what is UpdateCategory()? 

0
dekartsoft
11/28/2007 12:14:13 PM

I tried the code as I put on the place of UpdateCateogries() the ProductDataSource, but it still does not want to put the SelectedValue form the DDL into the object(Product) assigned to the row of the GridView.

0
dekartsoft
11/28/2007 1:12:42 PM

 UpdateCategory() is just a sample datasource... configure your own datasource and reference it to your grid like

 


Regards,Vinz

"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
0
vinz
11/29/2007 12:58:02 AM

can you post the codes?Please dont post all your codes, Just the relevant line one .


Regards,Vinz

"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
0
vinz
11/29/2007 1:00:52 AM

 OK.

 Thant's the code for the Template:

                            <asp:TemplateField HeaderText="Category">
                                <EditItemTemplate>
                                    <asp:DropDownList ID="dropdownlistCategory" runat="server"
                                        Width="139px" DataSourceID="ProductDataSource" DataTextField="CategoryName" DataValueField="CategoryID" SelectedValue='<%# Bind("CategoryID") %>'>
                                    </asp:DropDownList>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:DropDownList ID="dropdownlistCategoryIT" runat="server"
                                        Width="133px" DataSourceID="ProductDataSource" DataTextField="CategoryName" DataValueField="CategoryID" SelectedValue='<%# Bind("CategoryID") %>'>
                                    </asp:DropDownList>
                                </ItemTemplate>
                            </asp:TemplateField>

ObjectDataSource: 

                    <asp:ObjectDataSource ID="ProductDataSource" runat="server" DataObjectTypeName="Product"
                        DeleteMethod="Delete" SelectMethod="GetAll" TypeName="ProductList" UpdateMethod="Update">                      
                    </asp:ObjectDataSource>

Sorry for the not so specified questions, but I'm a nubbie in ASP .NET. So from all articles I read, I think the problem is with ObjectDataSource. I cannot manage to pass the new CategoryID to the Business Object(Product). The that Contributor wrote do not helped me either. Please, if someone has experienced with ObjectDataSource and has managed to achieve the Update command with parameters, to help me. I'm stuck with it for a long, long time.

Thanks 

0
dekartsoft
11/29/2007 7:32:17 AM

Why not use DataSet/DataTable as your DataSource and Bind your DLL based on the data returned in DataSet/DataTable?

The advantage of using DataSet/DataTable is that its easy for you to manipulate and handle datas  

If you are not familiar with those then have a read on this article

http://www.aspdotnetcodes.com/GridView_Insert_Edit_Update_Delete.aspx

 

 


Regards,Vinz

"Code, Beer and Music" that's my way of being a programmer!

How to get your Forum Question Answered | Blog | CodeASP.NET
0
vinz
11/29/2007 7:44:48 AM

 Because it seemed so easy to Bind the control to my Object and to have all the logic in the method rather Update or Select. But as I see it's not been made so easy and I'll try using the SQLDataSource as you suggest. Thanks for the replies.

0
dekartsoft
11/29/2007 7:54:37 AM

Hi dekartsoft ,

Have a look at my sample,

 

 

1    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
2                SelectMethod="GetAll" TypeName="WebApplication1.Dao" UpdateMethod="Update" OnUpdating="ObjectDataSource1_Updating" >
3                 <UpdateParameters>
4                <asp:Parameter Name="p" Type="Object"  />
5         
6                </UpdateParameters>
7                </asp:ObjectDataSource>
8                        </div>
9            <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="160px">
10               <Columns>
11                   <asp:CommandField ShowEditButton="True" />
12                   <asp:TemplateField>
13                       <EditItemTemplate>
14                            <asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource1"
15                               DataTextField="bid" DataValueField="bid">
16                           </asp:DropDownList>
17                       </EditItemTemplate>
18                       <ItemTemplate>
19                            
20                           <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"
21                               DataTextField="bid" DataValueField="bid">
22                           </asp:DropDownList>
23                       </ItemTemplate>
24                   </asp:TemplateField>
25               </Columns>
26           </asp:GridView>

 

1    protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
2            {
3                this.ObjectDataSource1.Update();
4            }
5    
6            protected void ObjectDataSource1_Updating(object sender, ObjectDataSourceMethodEventArgs e)
7            {
8    
9                int index = this.GridView1.EditIndex;
10   
11               DropDownList ddl = (DropDownList)this.GridView1.Rows[index].FindControl("DropDownList2");
12               string id = ddl.Text;
13   
14               Product p = new Product();
15   
16               p.id = Convert.ToInt32( id);
17               e.InputParameters["p"] =p;
18           }
 

Samu Zhang
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question.
0
Samu
11/29/2007 10:05:46 AM

 Hi Participiant,

Your code looks like it's gonna work, but there is one problem with it. The InputParameters dictionary is readonly and when I try to modify it it says:

"The OrderedDictionary is readonly and cannot be modified. "

And something else. What is SqlDataSource1 ? 

0
dekartsoft
11/29/2007 11:27:22 AM

Hi dekartsoft ,

SqlDataSource1 is another datasource control to be binded with gridview.

The sample works fine on my pc. But if it can not work on your pc, have a look at another solution.

 

 

1    <asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
2                SelectMethod="GetAll" TypeName="WebApplication1.Dao" DataObjectTypeName="WebApplication1.Product" UpdateMethod="Update" OnUpdating="ObjectDataSource1_Updating" >
3                 <UpdateParameters>
4                <asp:Parameter Name="p" Type="Object"  />
5         
6                </UpdateParameters>
7                </asp:ObjectDataSource>
8                        </div>
9            <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="160px">
10               <Columns>
11                   <asp:CommandField ShowEditButton="True" />
12                   <asp:TemplateField>
13                       <EditItemTemplate>
14                            <asp:DropDownList ID="DropDownList2" runat="server" DataSourceID="SqlDataSource1"
15                               DataTextField="bid" DataValueField="bid">
16                           </asp:DropDownList>
17                       </EditItemTemplate>
18                       <ItemTemplate>
19                            
20                           <asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1"
21                               DataTextField="bid" DataValueField="bid">
22                           </asp:DropDownList>
23                       </ItemTemplate>
24                   </asp:TemplateField>
25               </Columns>
26           </asp:GridView>

 

1    protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
2            {
3                this.ObjectDataSource1.Update();
4            }
5    
6            protected void ObjectDataSource1_Updating(object sender, ObjectDataSourceMethodEventArgs e)
7            {
8    
9                int index = this.GridView1.EditIndex;
10   
11               DropDownList ddl = (DropDownList)this.GridView1.Rows[index].FindControl("DropDownList2");
12               string id = ddl.Text;
13   
14               //Product p = new Product();
15   
16               //p.id = Convert.ToInt32( id);
17   
18               Product pp = (Product)e.InputParameters["p"];
19               pp.id = Convert.ToInt32(id);
20           }
 

Samu Zhang
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question.
0
Samu
11/29/2007 12:30:04 PM

I'm sure it works, but I can't get the idea of the sample. What's the need of ObjectDataSource when we have SqlDataSource. And  where do we bind the ObjectDataSource?

0
dekartsoft
11/29/2007 1:32:23 PM

Can't we pass the parameter from the DDL to the ObjectDataSource w/out using the SqlDataSource? 

0
dekartsoft
11/29/2007 1:33:42 PM

Hi dekartsoft ,

The sample is to explain how to pass parameter to the update method .

The sqldatasource is used for retrieve data from database and bind data to gridview then the dropdownlist can show them.

dekartsoft:
Can't we pass the parameter from the DDL to the ObjectDataSource w/out using the SqlDataSource? 

 

Sure, we can.

  • retrieve the parameter (Product pp = (Product)e.InputParameters["p"];)
  • set it's value (pp.id=Convert.ToInt32(id);)

SqldataSource in my page,

1    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues"
2                ConnectionString="<%$ ConnectionStrings:ConnectionString %>" DeleteCommand="DELETE FROM [bbbbbb] WHERE [bid] = @original_bid AND [bname] = @original_bname"
3                InsertCommand="INSERT INTO [bbbbbb] ([bid], [bname]) VALUES (@bid, @bname)" OldValuesParameterFormatString="original_{0}"
4                SelectCommand="SELECT * FROM [bbbbbb]" UpdateCommand="UPDATE [bbbbbb] SET [bname] = @bname WHERE [bid] = @original_bid AND [bname] = @original_bname" OnUpdating="SqlDataSource1_Updating">
5                <DeleteParameters>
6                    <asp:Parameter Name="original_bid" Type="Int64" />
7                    <asp:Parameter Name="original_bname" Type="String" />
8                </DeleteParameters>
9                <UpdateParameters>
10                   <asp:Parameter Name="bname" Type="String" />
11                   <asp:Parameter Name="original_bid" Type="Int64" />
12                   <asp:Parameter Name="original_bname" Type="String" />
13               </UpdateParameters>
14               <InsertParameters>
15                   <asp:Parameter Name="bid" Type="Int64" />
16                   <asp:Parameter Name="bname" Type="String" />
17               </InsertParameters>
18   </asp:SqlDataSource>
 

Samu Zhang
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question.
0
Samu
11/30/2007 1:48:38 AM
Reply:

Similar Artilces:

First gridview's selected row doesn't update second gridview's objectdatasource
 HelloI got 2 gridviews on a page, each with its own ObjectDataSource. The first gridview fills itself just normally, no problem there. The second gridview needs to fill itself with other data, where the primary key is the primary key of the selected row of the first gridview.schematically:gridview1 row: IDfield, x, y, zrow: IDfield, x, y, z (-> this row is selected)row: IDfield, x, y, z gridview2 row:IDfield_of_selected_row_in_gridview1, a, b, c I tried to do this by configuring the ObjectDataSource behind gridview2 with a parameter pointing to gridview1.selectedValue. (by usin...

Default value for Dropdownlist that get's it's value from Database.
Hi, I am using an Object Data Souce to retrieve the value of a Dropdownlist from a table on MS SQL server 2005. I want to make a default value appear on the Dropdownlist intially, should i enter the default value into the database table or is that a better way of doing it? Any suggestions will be very much appreciated. E  No need for database just set sekected value after databingind protected void Page_Load(object sender, EventArgs e) { DataBind(); ListItem defaultItem = new ListItem("Select a Person", "-1"); th...

Dropdownlist's Value Updates Another Dropdownlist's list
Hi, I'm looking for the best way to update a dropdownlist's list based on a value choosen from another dropdownlist on the page. A common example of this is there are two DDLs.  One for state and one for county.  The county DDL is left blank until a state is choosen.  Once a state is choosen then the county dropdownlist is filled. Now here is part of my dilemma.  I'm entered other data on the form, so if I postback I need some way of knowing that the postback is just for the purpose of filling the secont dropdownlist.  In addition everytime that first DDL is change...

Getting DropDownlist's DataTextValue Selected Value Given the SelectedValue and/or Selected Item
In the vb.net codebehind, I need to extract something from the Text (displayed) value of dropdownlist's selected item and I have  the SelectedValuand and SelectedItem in hand. How can I do this?  FindControl? Item? row?   Thanks. Well, its easier than you might think. SelectedItem has a "text" property. Thats the selected text right there :)  If you need the Text of the selection, then you have to use the SelectedItem.Text property.  If you want the value (not the displayed text) the you can directly use the SelectedValue. dim sText as String = dropdown...

cant't get value from a dropdownList in DetailsView's TemplateField on update or insert mode
i insert a DropdownList into the detailview' InsertItemTemplate,and  want to the detailview can fetch the value of the DropdownList which i select. But i do not know how to code it.   Should i use the <asp:ControlParamete> section of  the ObjectDataSource? how to i  set the value of it's ControlID property? my code is  here: <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">    <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="100%" AutoGenerateRows="False"   &nb...

dropdownlist's selected index value is not printing the selected value
Here iS my code .Aspx Page <asp:DropDownList ID="ddlkeyword" runat="server" Width="204px" DataTextField="Form" DataValueField="Form" OnSelectedIndexChanged="ddlkeyword_SelectedIndexChanged" >   </asp:DropDownList> <asp:Button ID="Button1" runat="server" Text="Submit" Width="110px" OnClick="Button1_Click" /> my aspx.cs protected void Page_Load(object sender, EventArgs e) { fillddlkeyword(); }protected void Page_Init(object sender, EventArgs e) { ...

getting at a controls value where it's embeded like
UpdatePanel > ContentTemplate > GridView i'm trying to say if the hyperlink in the gridviews template endswith ".pdf" show an imagebutton that is a pdf icon. this was my feable attempt. ImageButton IBSamp;IBSamp = (ImageButton)UpdatePanel1.FindControl("IBSample");HyperLink HLSamp;HLSamp = (HyperLink)UpdatePanel1.FindControl("HyperLink3").ToString();if(HLSamp.ToString().EndsWith("pdf")){IBSamp.Visible = true;} Hi! In the GridView you can try something like this:<asp:TemplateField HeaderText="Image" SortExpression="...

How To Get the Gridview's Field Value if the Column's Visible=False..?
Here is the scenario: My sql query returns Name, ID, SSNum. I use a gridview which has 3 columns Name, ID and SSNum (with SSNum is set visible=false) so the gridview only shows Name and ID. I need to use part of SSNum to form a NewUserID in the code behind. Im doing this by using the gvResult_OnRowDataBound. So far, if I set SSNum column's visible=false then I wont see this field on row data bound. Any suggestion as how to obtain this SSNum from the code behind?  you can set it as the datakey on the properties of the grid view and use this codethis.GridView1.DataKeys[this.Gri...

obtain ANY control's (textbox/dropdown) value in GridView's HeaderTemplate
Given this templated GridView column containing either Textbox's or DropDownLists......          <asp:TemplateField >              <HeaderTemplate>                      <asp:TextBox ID="TextBoxWellName" runat="server"  Visible="False" l"></asp:TextBox>           &nb...

Help! I cannot access the DataGrid's ItemTemplate's LinkButton's Text Atrribute 's Value!!!!!!!!!!!
I write a datagrid's ItemDataBound method as follows:   private void dgTable_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)  {   if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)   {    if(!isRole("Manager"))    {     LinkButton tmp = (LinkButton)e.Item.FindControl("lbPassed");     if(tmp.Text == "Passed")     {      ((LinkBu...

Getting Repeater's EVAL value from within DropDownList's SelectedIndexChanged sub
Hello, I placed the dropdownlist directly into Repeater's ItemTemplate like this: <asp:Repeater ID="rptOrderHistory" runat="server" DataSourceID="sqlDS_OrderHistoryList"> <ItemTemplate> <tr> <td><img src="../images/Icon_Gentleman.jpg" /><br /><%#Eval("UserID").ToString.PadLeft(5, "0"c)%></td> <td><img src="../images/Icon_Parcel.jpg" /><br /><%#Eval("OrderID").ToString....

I can't get value of control in the selected row of a Gridview
I'm trying to perform an update using a sqldatasource from a gridview after a selection is made from a dropdown and a linkbutton "lbnUpdate" is clicked. I assigned  "select" as the command name of the linkbutton so I was assuming that I could then reference the gridviews selected row from the code behind but I guess I made a bad assumption. During debug there is "nothing" in the variable I use to capture the gridview selected row. I will post what I have. If I set AutoGenereateSelect button to true I can get the SelectedIndexChanged event...

What's wrong with DataBind() in GridView control? The data in GridView can't be updated when the datasource have changed!
What's wrong with DataBind() in GridView control? The data in GridView can't be updated when the datasource have changed! I bind the different datasource to the Gridview when I change the node of TreeView, the GridView control always display the same data when I click different the node of TreeView control,why?but I can get the different data in GridView when I click the Button1 or Button2. //-------------------Program Code (You may save it as a ASPX file and run it)--------------------------------<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http:/...

Programmatically reading the selected value of DropDownList in Gridview's Template field
Hi all, I'm reading the content of 2 fields in a Gridview programmatically. For text box, I'm successful with   inv1 = CType(GV_Rows(e.RowIndex).Cells(7).Controls(0), TextBox) follow by a=inv1.text for dropdownlist, I have problem. My code is: inv2 = CType(GV.Rows(e.RowIndex).Cells(6).Controls(0), DropDownList) b=inv2.SelectedValue.Trim  HOwever I run into error: "Unable to cast object of type UI.LiteralCOntrol to type WebControls.DropDownList" Plse help... THank you very much. TOny Instead of using inv2 = CType(GV.Rows(e.RowIndex).Cells(6).Controls(0)...

Web resources about - Getting the selected value from an embedded DropDownList in GridView's ItemTemplate when Updating - asp.net.presentation-controls

Resources last updated: 1/8/2016 7:11:43 AM