Domanda

I have been trying the whole day to fix this, hope someone can give me an answer! (please keep in mind I'm a beginner in this coding). I have a database where one of the fields is an imageurl. I have to be able to update this field and thought that I could do so using a GridView with an UpdateItemTemplate. I soon found out that you have to use the FindControl recursive method to do so - so I implemented the code and I'm now stuck with another error.

I think I know why the error appears, but have no idea how to fix it. It seems that in the tools.cs file the identifier of the control is set to be of data type String, but I have no clue what to do with a FileUpload.

Here is the error message:

cannot convert from 'System.Web.UI.WebControls.FileUpload' to 'string'

ASP.NET GridView control:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
  DataKeyNames="DrinkCategoryID" DataSourceID="ObjectDataSource1">
  <Columns>
    <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
    <asp:BoundField DataField="DrinkCategoryID" HeaderText="DrinkCategoryID" 
      InsertVisible="False" ReadOnly="True" SortExpression="DrinkCategoryID" />
    <asp:TemplateField HeaderText="DrinksCategoryName" 
      SortExpression="DrinksCategoryName">
    <EditItemTemplate>
      <asp:FileUpload ID="FileUpload1" runat="server" />
    </EditItemTemplate>
    <ItemTemplate>
      <asp:Label ID="Label1" runat="server" 
        Text='<%# Bind("DrinksCategoryName") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

The tool (FindControl)

public static Control FindControlRecursive(Control Root, string Id)
{
  if (Root.ID == Id)
    return Root;

    foreach (Control Ctl in Root.Controls)
    {
      Control FoundCtl = FindControlRecursive(Ctl, Id);
      if (FoundCtl != null)
        return FoundCtl;
    }

    return null;
}

And code behind for the web form (click event for the save button)

protected void btnGem_Click(object sender, EventArgs e)
{
  FileUpload FileUpload1 = (FileUpload)Tools.FindControlRecursive(
    GridView1, FileUpload1);
  //This seems to work fine
  TextBox txtBox = (TextBox)Tools.FindControlRecursive(GridView1, txtBox.Text);
}
È stato utile?

Soluzione

On the first line of your button handler, you're passing the control itself as the second parameter of FindControlRecursive - you need to pass in the string ID of the control you're looking for. In other words:

 protected void btnGem_Click(object sender, EventArgs e)
    {
        FileUpload FileUpload1 = (FileUpload)Tools.FindControlRecursive(GridView1, "FileUpload1");
TextBox txtBox = (TextBox)Tools.FindControlRecursive(GridView1, txtBox.Text); //This seems to work fine

    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top