Reference certain control in gridview

Last post 07-16-2009 7:21 AM by alessandro. 10 replies.

Sort Posts:

  • Reference certain control in gridview

    07-11-2009, 2:08 AM
    • Member
      32 point Member
    • Cza102282
    • Member since 10-26-2006, 11:48 PM
    • Posts 105

    I have a gridview that has several 7 fileupload controls with a button and a radio button list under each.  I would like to avoid writing the same code 7 times to accomplish what I need so I need a way to reference which fileupload and radio buttonn list should be used when the button is clicked underneath.

                            <asp:TemplateField HeaderText="Main Picture">
                                <EditItemTemplate>
                        <img alt="" runat="server" src='<%# DataBinder.Eval(Container, "DataItem.picURLThumb") %>' id="Img11"/>
                        <asp:FileUpload ID="FileUpload1" runat="server" /><br />
                                  <asp:Button ID="Button1" runat="server" CommandArgument='<%# Container.DataItemIndex  %>'
                            Text="Upload" OnClick="Button1_Click" /><br /><asp:RadioButtonList ID="rblPicType" runat="server">
                                    <asp:ListItem Selected="True" Value="0">Portrait</asp:ListItem>
                                    <asp:ListItem Value="1">Landscape</asp:ListItem>
                                    </asp:RadioButtonList>        
                                </EditItemTemplate>
                            </asp:TemplateField>

    The following line of code cannot be used since the FileUpload control name needs to be different for each.

    Dim file As FileUpload = DirectCast(GridView1.Rows(index).FindControl("FileUpload1"), FileUpload)


    What can I do??

  • Re: Reference certain control in gridview

    07-11-2009, 6:21 AM
    • Contributor
      6,788 point Contributor
    • alessandro
    • Member since 06-25-2002, 10:05 AM
    • Italy
    • Posts 1,103

    All files uploaded can be referenced in a collection available to you via the request object : Request.Files which returns HttpFileCollection. More with sample code can be found at the following document on msdn :

    http://msdn.microsoft.com/en-us/library/system.web.httpfilecollection.aspx

    This way you do not need to reference fileupload controls manually.

    Alessandro Zifiglio
    www.jiffycms.net - opensource HTML Editor for ASP.NET
    http://weblogs.asp.net/alessandro


    In the land of the blind, the man with one eye is king!:x
  • Re: Reference certain control in gridview

    07-11-2009, 9:46 AM
    • Member
      32 point Member
    • Cza102282
    • Member since 10-26-2006, 11:48 PM
    • Posts 105

    What about the radiobuttonlist??

  • Re: Reference certain control in gridview

    07-11-2009, 10:07 AM
    • Contributor
      6,788 point Contributor
    • alessandro
    • Member since 06-25-2002, 10:05 AM
    • Italy
    • Posts 1,103

     protected void Button1_Click(object sender, EventArgs e)
        {
            Button b = (Button)sender;
            GridViewRow gvr = (GridViewRow)b.NamingContainer;
            RadioButtonList rdl = gvr.FindControl("rblPicType");
            if (rdl != null)
            {
                foreach (ListItem li in rdl.Items)
                {
                    if (li.Selected)
                    {
                        //do something
                    }
                }
            }
        }

    Alessandro Zifiglio
    www.jiffycms.net - opensource HTML Editor for ASP.NET
    http://weblogs.asp.net/alessandro


    In the land of the blind, the man with one eye is king!:x
  • Re: Reference certain control in gridview

    07-11-2009, 10:14 AM
    • Contributor
      6,788 point Contributor
    • alessandro
    • Member since 06-25-2002, 10:05 AM
    • Italy
    • Posts 1,103

     At this point, I wonder what your original question was because you can do the same thing I did with your radiobuttonlist to your fileupload control as well, that is to use findcontrol and reference it in that manner on button click.

    ohh and i'm just noticing your vb.net syntax so just run my code through an online c# to vb.net converter. Plenty available freely online.

    Why do you think you have to repeat your code 7 times? afterall, there is only 1 fileuplaod and 1 radiobuttonlist per row.

    Alessandro Zifiglio
    www.jiffycms.net - opensource HTML Editor for ASP.NET
    http://weblogs.asp.net/alessandro


    In the land of the blind, the man with one eye is king!:x
  • Re: Reference certain control in gridview

    07-11-2009, 7:37 PM
    • Member
      32 point Member
    • Cza102282
    • Member since 10-26-2006, 11:48 PM
    • Posts 105

    Actually, the way I am approaching it as of right now, there are seven fileuploads in a row.  They each correspond to field in my database as picture1, picture 2 and so on.  I realize this is not efficient data design but the customer expressed only needing 7 slots for pictures.

    That is why I was asking about a the possiblility of using a function to pass the id of the fileupload and radiobuttonlist too.

  • Re: Reference certain control in gridview

    07-11-2009, 7:48 PM
    • Contributor
      6,788 point Contributor
    • alessandro
    • Member since 06-25-2002, 10:05 AM
    • Italy
    • Posts 1,103

    ahh i see. Ok cool. Basically as part of your declarative code, i only saw one fileupload control, which is why I felt i needed to ask :-)

    So use the Files collection in the Request object for the file uploads since there can be 7 file uploads per row, while access the radiobuttonlist as i showed you in the previous post. There is no need to access the fileupload control by id.

    If you need to look at working code, here's another sample on msdn, scroll down to the section "Uploading multiple files at a time" :

    http://msdn.microsoft.com/en-us/library/aa478971.aspx

    I think the previous example was a bit scarse, let me know if something is not clear.

    Alessandro Zifiglio
    www.jiffycms.net - opensource HTML Editor for ASP.NET
    http://weblogs.asp.net/alessandro


    In the land of the blind, the man with one eye is king!:x
  • Re: Reference certain control in gridview

    07-14-2009, 10:23 PM
    • Member
      32 point Member
    • Cza102282
    • Member since 10-26-2006, 11:48 PM
    • Posts 105

    Okay.  I am finally back and I am sorry to report I am having no luck with your suggestions.

    First off, I need a radiobuttonlist in each of the 7 columns that I have file upload controls for.  Therefore I cannot use the code line suggested above...

    RadioButtonList rdl = gvr.FindControl("rblPicType");

    I cannot have 7 controls named rblPicType.  I need a way to distinguish and represent each one separately.


    Secondly, I tried using the 'Uploading multiple files at a time' sample exactly and I am getting an "Out of memory" error.  I was only uploading with one of the file uploads.


    I must be clearly wrong when I was figuring the solution could be as easy making a reference to the row and column position and than being able to access the controls.  I also thought the same kind of logic could be applied when you have multiple controls of any type in a row.


    Is it possible I am not explaining myself clear enough???


    How about this?  Is there a way to get the index of the cell that holds the button that was clicked??  That way I could build a string to represent the control name based on the cell index.  Something like...

    Dim s as string = "FileUpload"

    Dim i as integer = 'code to get cell index of button click

    Dim idOfControl = s + i

    I would just have to make sure that my controls are name correctly for the column that they are in.


  • Re: Reference certain control in gridview

    07-15-2009, 1:42 PM
    Answer
    • Contributor
      6,788 point Contributor
    • alessandro
    • Member since 06-25-2002, 10:05 AM
    • Italy
    • Posts 1,103

    well, if you got unpredictable ids as you state, since in each column you'll have to place a fileupload+radiobuttonlist+button, with 7 columns in all, well, the easiest thing to do is store the ids with the button's CommandArgument property and then after the postback, retriev the id and do what you want to go about doing :

     <asp:TemplateField HeaderText="Field1">
                        <ItemTemplate>
                            <asp:FileUpload ID="FileUpload1" runat="server" />
                            <asp:RadioButtonList ID="RadioButtonList1" runat="server">
                            </asp:RadioButtonList>
                            <asp:Button ID="Button1" runat="server" CommandArgument="Fileupload1:RadioButtonList1" Text="FileUpload" OnCommand="Button_Command" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Field2">
                        <ItemTemplate>
                            <asp:FileUpload ID="FileUpload2" runat="server" />
                            <asp:RadioButtonList ID="RadioButtonList2" runat="server">
                            </asp:RadioButtonList>
                            <asp:Button ID="Button2" runat="server" CommandArgument="Fileupload2:RadioButtonList2" Text="FileUpload" OnCommand="Button_Command" />
                        </ItemTemplate>
                    </asp:TemplateField>
        ...more templatefiles if you may..


    note that they all call the same Button_Command handler, that's pretty much what you'd do declaratively.

    And then imperatively, you'd handle the OnCommand event handler like this :

    protected void Button_Command(object sender, CommandEventArgs e)
        {
            Button b = (Button)sender;
            GridViewRow gvr = (GridViewRow)b.NamingContainer;
            string[] commands = e.CommandArgument.ToString().Split(':');
            FileUpload fu = (FileUpload)gvr.FindControl(commands[0]);
            RadioButtonList rdl = (RadioButtonList)gvr.FindControl(commands[1]);
            if (fu != null)
            {
                //file upload found
            }
            if (rdl != null)
            {
                //radiobuttonlist found
            }
        }


    Note that, first we retrieve the GridViewRow, to get this we go through the namingcontainer of the button (that fired the event). Afterall we want the row in which the button was clicked.

    Next notice the commandArgument, this contains the id of the control you are interested in :

     CommandArgument="Fileupload1:RadioButtonList1"

    so in the event handler, we split on this to get our id :

    string[] commands = e.CommandArgument.ToString().Split(':');

    and then you go about doing findcontrol and whatever it is you wanted to get going.

    Now, if you find this somehow problematic for you, explain in detail what the problem is, also try to create a small contained project that shows the problem in full. Below I paste you self contained code, i expect for you to reproduce you problem using the code provided below or having similar testable code that I can simply throw in a page and run and verify.

    Also as per your error message about running out of memory, that's unrelated to the post you started. This depends on a lot of different things eg :

    1)version of iis in use
    2)maxRequestLength
    3)executionTimeout
    4)maxAllowedContentLength
    4)if iis7, then the requestFiltering and overrideModeDefault configuration in applicationHost.config

    for all these, i suggest you do some homework first, attempt to understand what is causing your out of memory problem and diagnose it, here are a few leads that can help you :

    http://forums.iis.net/p/1108662/1702390.aspx

    http://msdn.microsoft.com/en-us/library/ms689462.aspx

    http://msdn.microsoft.com/en-us/library/e1f13641.aspx


    <%@ Page Language="C#" %>

    <%@ Import Namespace="System.Data" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
    Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <script runat="server">
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GridView1.DataSource = CreateDataSource();
                GridView1.DataBind();
            }
        }

        ICollection CreateDataSource()
        {
            DataTable dt = new DataTable();
            DataRow dr;

            dt.Columns.Add(new DataColumn("Field1", typeof(string)));
            dt.Columns.Add(new DataColumn("Field2", typeof(string)));
            dt.Columns.Add(new DataColumn("Field3", typeof(string)));
            for (int i = 0; i < 10; i++)
            {
                dr = dt.NewRow();
                dr[0] = "Field1 " + i.ToString();
                dr[1] = "Field2 " + i.ToString();
                dr[2] = "Field3 " + i.ToString();
                dt.Rows.Add(dr);
            }
            DataView dv = new DataView(dt);
            return dv;
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                for (int num1 = 1; num1 < 4; num1++)
                {
                    string id = string.Format("RadioButtonList{0}", num1);
                    RadioButtonList rdl = (RadioButtonList)e.Row.FindControl(id);
                    if (rdl != null)
                    {
                        rdl.DataSource = new string[] { "apples","bananas","grapes"};
                        rdl.DataBind();
                    }
                }
            }
        }
     
        protected void Button_Command(object sender, CommandEventArgs e)
        {
            Button b = (Button)sender;
            GridViewRow gvr = (GridViewRow)b.NamingContainer;
            string[] commands = e.CommandArgument.ToString().Split(':');
            FileUpload fu = (FileUpload)gvr.FindControl(commands[0]);
            RadioButtonList rdl = (RadioButtonList)gvr.FindControl(commands[1]);
            if (fu != null)
            {
                Response.Write("<br />" + fu.ID);
            }
            if (rdl != null)
            {
                Response.Write("<br />" + rdl.ID);
            }
        }
    </script>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" AutoGenerateColumns="false"
            runat="server" OnRowDataBound="GridView1_RowDataBound">
                <Columns>
                    <asp:TemplateField HeaderText="Field1">
                        <ItemTemplate>
                            <asp:FileUpload ID="FileUpload1" runat="server" />
                            <asp:RadioButtonList ID="RadioButtonList1" runat="server">
                            </asp:RadioButtonList>
                            <asp:Button ID="Button1" runat="server" CommandArgument="Fileupload1:RadioButtonList1"
    Text="FileUpload" OnCommand="Button_Command" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Field2">
                        <ItemTemplate>
                            <asp:FileUpload ID="FileUpload2" runat="server" />
                            <asp:RadioButtonList ID="RadioButtonList2" runat="server">
                            </asp:RadioButtonList>
                            <asp:Button ID="Button2" runat="server" CommandArgument="Fileupload2:RadioButtonList2"
    Text="FileUpload" OnCommand="Button_Command" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Field3">
                        <ItemTemplate>
                            <asp:FileUpload ID="FileUpload3" runat="server" />
                            <asp:RadioButtonList ID="RadioButtonList3" runat="server">
                            </asp:RadioButtonList>
                            <asp:Button ID="Button3" runat="server" CommandArgument="Fileupload3:RadioButtonList3"
    Text="FileUpload" OnCommand="Button_Command" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </div>
        </form>
    </body>
    </html>

    Alessandro Zifiglio
    www.jiffycms.net - opensource HTML Editor for ASP.NET
    http://weblogs.asp.net/alessandro


    In the land of the blind, the man with one eye is king!:x
  • Re: Reference certain control in gridview

    07-16-2009, 12:47 AM
    • Member
      32 point Member
    • Cza102282
    • Member since 10-26-2006, 11:48 PM
    • Posts 105

    Yes, that is exactly what I was looking for.   I can see myself reusing this logic in the future (Command Arguments for Buttons).

    I actually forgot to mention the other parameters I needed to pass (the names of the data columns for the SQL statement to save the image paths).  All I needed to do was add two other things to the command arguments and that was it.

    As for the 'out of memory' issue, I really didn't need to bring that up.  I jumped the gun a little.  I went back to the methods I was using before to resize the images and they are working fine.  I now have the issue of the quality reduction when saving thumbnail images.  I have ran into some solutions which allow you to resize without distortion but those will only resize proportionally.  That would not work if I wanted to give the user the option of resizing via Landscape or Portrait.  I am glad I have gotten over this hurdle for now.

    Thanks a lot buddy for sticking with me on this one.

  • Re: Reference certain control in gridview

    07-16-2009, 7:21 AM
    • Contributor
      6,788 point Contributor
    • alessandro
    • Member since 06-25-2002, 10:05 AM
    • Italy
    • Posts 1,103

    cool LaughingLaughing

    thanks for reporting back Wink



    Alessandro Zifiglio
    www.jiffycms.net - opensource HTML Editor for ASP.NET
    http://weblogs.asp.net/alessandro


    In the land of the blind, the man with one eye is king!:x
Page 1 of 1 (11 items)