Gridview templaye button control

Discussion in 'ASP .Net Web Controls' started by Morris Neuman, Dec 9, 2008.

  1. Hi,

    I have a gridview (GridView1) which has several bound fields. One of the
    fields (DirectoryListing) is a template field. In the Edit template field, I
    have a textbox (TextBox1), a fileupload control (FileBrowse1) and a button
    control (SelectButton).

    Definition of GridView1 Template Field
    <asp:TemplateField HeaderText="DirectoryListing"
    SortExpression="DirectoryListing">
    <EditItemTemplate>
    <asp:TextBox ID="TextBox1" runat="server"
    Text='<%# Bind("DirectoryListing") %>'
    Width="128px"></asp:TextBox>
    <br />
    <asp:FileUpload ID="FileSelect" runat="server" />

    <asp:Button ID="SelectButton" runat="server"
    onclick="SelectButton_Click"
    Text="Select File" />
    </EditItemTemplate>
    <ItemTemplate>
    <asp:Label ID="Label1" runat="server" Text='<%#
    Eval("DirectoryListing") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>


    In edit mode, the user can click on FileBrowse1 and select a file, then they
    can click on the SelectButton to move FileBrowse1.PostedFile.FileName to the
    TextBox1.

    I created a SelectButten_Click event as follows:

    protected void SelectButton_Click(object sender, EventArgs e)
    {
    TextBox1.Text = FileBrowse1.PostedFile.FileName.ToString();
    }

    I get error:
    Compilation Error
    Description: An error occurred during the compilation of a resource required
    to service this request. Please review the following specific error details
    and modify your source code appropriately.

    Compiler Error Message: CS0103: The name 'TextBox1' does not exist in the
    current context

    Source Error:



    Line 89: protected void SelectButton_Click(object sender, EventArgs e)
    Line 90: {
    Line 91: TextBox1.Text = FileBrowse1.PostedFile.FileName.ToString();
    Line 92: }
    Line 93:
    Source File:
    c:\Inetpub\wwwroot\CMWebManager\SystemAdminOnly\Copies\Test-with Butto_Click
    Examples.aspx Line: 91


    If I have a TextBox, FileUpload and Butten controls outside of a template
    control, the above works. I just don't know how to reference the controls
    triggered by a click event from inside a template control.

    Any help would be appreciated.
     
    Morris Neuman, Dec 9, 2008
    #1
    1. Advertisements

  2. Hi Morris,

    Since the TextBox and the FileUpload controls are put in the EditTemplate
    we cannot use their ID directly to get the reference of them.

    To achieve the requirement we can try following code:

    protected void SelectButton_Click(object sender, EventArgs e)
    {

    Button b = (Button)sender;
    TextBox tb= b.FindControl("TextBox1") as TextBox;
    FileUpload fu = b.FindControl("FileSelect") as FileUpload;
    if (tb != null&&fu!=null)
    {
    tb.Text = fu.PostedFile.FileName;
    }
    }

    In the above code, we get the sender first. Since it's triggered by the
    SelectButton the sender is the SelectButton. Now we've got the reference of
    this button and can use the Control.FindControl method to get the reference
    of the TextBox and the FileUpload controls. The FindControl method will
    search through the naming container of the caller control to find the
    control we need.

    Here's the documentation about FindControl method:
    http://msdn.microsoft.com/en-us/library/486wc64h.aspx

    Please let me know if it works and feel free to ask if you need further
    assistance.

    Regards,
    Allen Chen
    Microsoft Online Community Support

    Delighting our customers is our #1 priority. We welcome your comments and
    suggestions about how we can improve the support we provide to you. Please
    feel free to let my manager know what you think of the level of service
    provided. You can send feedback directly to my manager at:
    .

    ==================================================
    Get notification to my posts through email? Please refer to
    http://msdn.microsoft.com/en-us/subscriptions/aa948868.aspx#notifications.

    Note: MSDN Managed Newsgroup support offering is for non-urgent issues
    where an initial response from the community or a Microsoft Support
    Engineer within 2 business day is acceptable. Please note that each follow
    up response may take approximately 2 business days as the support
    professional working with you may need further investigation to reach the
    most efficient resolution. The offering is not appropriate for situations
    that require urgent, real-time or phone-based interactions. Issues of this
    nature are best handled working with a dedicated Microsoft Support Engineer
    by contacting Microsoft Customer Support Services (CSS) at
    http://msdn.microsoft.com/en-us/subscriptions/aa948874.aspx
    ==================================================
    This posting is provided "AS IS" with no warranties, and confers no rights.
     
    Allen Chen [MSFT], Dec 9, 2008
    #2
    1. Advertisements

  3. Thanks much. Worked perfectly.

    I question. Instead of using Browse to get the file name, then clicking
    Select to set TextBox1 to the name of the file selected, is there an event
    that can be trigerred when the file name field of the FileUpload control
    changes? I want to see if I can eliminate the user hving to click the Select
    button to set the value for the TextBox1.

    Once again, I appreciate the help. I am learning by your examples and
    moving well on my project.
     
    Morris Neuman, Dec 9, 2008
    #3
  4. Hi Morris,

    To do this we need to call JavaScript. The key point is to find the
    ClientID of the TextBox on the current row. The code is as below:

    Aspx:
    <head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">

    function ChangeValue(sender, i)
    {
    var t=i.id
    document.getElementById(t).value=sender.value;
    }
    </script>

    </head>

    ...................

    <asp:FileUpload ID="FileSelect" runat="server" onchange='<%#
    "ChangeValue(this,"
    +((GridViewRow)Container).FindControl("TextBox1").ClientID + ")"%>'/>

    ...................

    If you have further questions please feel free to ask.

    Regards,
    Allen Chen
    Microsoft Online Community Support
     
    Allen Chen [MSFT], Dec 10, 2008
    #4
  5. Thanks, worked perfectly. Where would I find documentation that onchange is
    a valid property for the FileUpload control? I tried to search but could not
    find it.

    One more question related to this fileupload control, can it be bound to a
    field in a table? So on edit if the bound field has a value then the file
    path and name would show in the textbox component of the fileupload. The
    user can then click on browse button to select a new file. On the gridview
    update button the value in the textbox component would be saved to the bound
    field. If this is possible then it would eliminate the need to have a
    seperate textbox that is in turn bound to a field.

    Once again Allen, you have been most responsive and extremely helpful.
     
    Morris Neuman, Dec 11, 2008
    #5
  6. Hi Morris:

    Quote from Morris =================================================

    Thanks, worked perfectly. Where would I find documentation that onchange
    is
    a valid property for the FileUpload control? I tried to search but could
    not
    find it.
    =================================================

    The asp:FileUpload control will render <input type="file" />. From the
    following documentation we can see onchange is supported by fileupload.
    http://www.w3schools.com/htmldom/event_onchange.asp

    Quote from Morris =================================================
    One more question related to this fileupload control, can it be bound to a
    field in a table? So on edit if the bound field has a value then the file
    path and name would show in the textbox component of the fileupload.
    =================================================

    As far as I know, due to security reason, we cannot assign a value to the
    fileupload. It can only be assigned by user interaction. If it's allowed a
    malicious server can easily steal any file he wants to get from the client.


    If you have further questions please feel free to ask.

    Regards,
    Allen Chen
    Microsoft Online Community Support
     
    Allen Chen [MSFT], Dec 11, 2008
    #6
  7. Thanks for the info.

    Is there anyway that I can find detailed properties of the file to be
    uploaded? We may need to upload .wav files but their detailed properties
    need ot be 11 KHz 8bit mono. I use the
    System.IO.Path.GetExtension(FileUploadExcel.PostedFile.FileName) to check for
    the extension before uploading but I need more specifics. I did not find
    anything when searching for System.IO.Path members.
     
    Morris Neuman, Dec 15, 2008
    #7
  8. Hi Morris,

    Thanks for your update.

    To do this we can refer to the WAVE format:
    http://ccrma.stanford.edu/CCRMA/Courses/422/projects/WaveFormat/

    We can get all the bytes of the wav file at server side via
    .FileUpload.FileBytes.
    Here's a sample that demonstrates how to achieve the requirement:

    Aspx:
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button1" runat="server"
    Text="Upload" onclick="Button1_Click" />

    Aspx.cs:
    protected void Button1_Click(object sender, EventArgs e)
    {
    bool _ismono = false;
    int _samplerate = 0;
    int _bitspersample = 0;
    byte[] filebytes= this.FileUpload1.FileBytes;
    if (filebytes.Length >
    44&&this.FileUpload1.FileName.ToLower().EndsWith(".wav"))
    {
    _ismono = filebytes[22] == 1 && filebytes[23] == 0;
    byte[] samplerate = new byte[4] { filebytes[24],
    filebytes[25], filebytes[26], filebytes[27] };
    _samplerate = BitConverter.ToInt32(samplerate, 0);
    byte[] bitspersample = new byte[2] { filebytes[34],
    filebytes[35] };
    _bitspersample = BitConverter.ToInt16(bitspersample, 0);
    }
    }

    If you like you can also read other chunks in the above way.

    Please have a try and let me know if it works and feel free to ask if you
    need further assistance.

    Regards,
    Allen Chen
    Microsoft Online Support
     
    Allen Chen [MSFT], Dec 16, 2008
    #8
  9. Thanks. I will try this in the new few days and let you know.

    Is there anyway to get this info before uploading file? I use the following
    to check the extension of the file selected for upload, so can I check other
    properties before uploading?

    String strFileExt =
    System.IO.Path.GetExtension(FileUploadExcel.PostedFile.FileName);
    if (strFileExt == ".xls" || strFileExt == ".wav")
     
    Morris Neuman, Dec 17, 2008
    #9
  10. Hi Morris,

    Morris ==================================================
    Is there anyway to get this info before uploading file?
    ==================================================

    To achieve this requirement we need to check the file at client side.
    ASP.NET is not the proper technique for this task since ASP.NET code runs
    at server side. What we need is a RIA(Rich Internet applications) technique
    such as Silverlight.

    Here's the Silverlight code that can achieve the requirement:

    XAML:
    <StackPanel>
    <TextBlock x:Name="TextBlock1"></TextBlock>
    <Button Width="100" Height="50" Click="Button_Click"
    Content="Select File"></Button>
    </StackPanel>
    XAML.cs:
    private void Button_Click(object sender, RoutedEventArgs e)
    {
    // Create open file dialog box
    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.Filter = "Wav File(*.WAV)|*.WAV";
    openFileDialog1.FilterIndex = 1;

    if (openFileDialog1.ShowDialog() == true)
    {
    //Open the selected file to read.
    using (System.IO.Stream fileStream =
    openFileDialog1.File.OpenRead())
    {

    bool _ismono = false;
    int _samplerate = 0;
    int _bitspersample = 0;
    byte[] filebytes = new byte[(int)fileStream.Length];
    fileStream.Read(filebytes, 0, filebytes.Length);
    if (filebytes.Length > 44)
    {
    _ismono = filebytes[22] == 1 && filebytes[23] == 0;
    byte[] samplerate = new byte[4] { filebytes[24],
    filebytes[25], filebytes[26], filebytes[27] };
    _samplerate = BitConverter.ToInt32(samplerate, 0);
    byte[] bitspersample = new byte[2] { filebytes[34],
    filebytes[35] };
    _bitspersample =
    BitConverter.ToInt16(bitspersample, 0);

    }
    TextBlock1.Text = String.Empty;
    TextBlock1.Text += _ismono ? "This WAV is Mono" : "This
    WAV is not Mono";
    TextBlock1.Text += "\r\nSample rate is: " + _samplerate;
    TextBlock1.Text += "\r\nBit sample rate is: " +
    _bitspersample;

    //Decide whether to upload this file here
    //You can upload the filebytes to server
    }
    }
    }

    You can get started to learn Silverlight from here:
    http://silverlight.net/

    Please feel free to ask if you have further questions.
    Regards,
    Allen Chen
    Microsoft Online Support
     
    Allen Chen [MSFT], Dec 18, 2008
    #10
  11. Hi Morris,

    Do you have any progress on this issue? If you have any questions please
    don't hesitate to let me know.

    Regards,
    Allen Chen
    Microsoft Online Support
     
    Allen Chen [MSFT], Dec 22, 2008
    #11
  12. Hi Allen,

    Sorry but I have not tried this yet. I willtry in a few days and if there
    are any issues/questions I will let you know.
     
    Morris Neuman, Dec 22, 2008
    #12
  13. Hi Morris,

    How's everything going?

    I would appreciate it if you could drop me a note to let me know the status
    of the issue in the thread. If you have any questions or concerns, please
    feel free to let me know. I am happy to be of assistance.

    Regards,
    Allen Chen
    Microsoft Online Support
     
    Allen Chen [MSFT], Dec 29, 2008
    #13
  14. Hi Allen,

    The upload, file browse button worked. Thanks.

    I have not started to learn about Silver Light so have not tried the wav
    file check code..

    Where would I insert the XAML code or how do I create this file type?
     
    Morris Neuman, Jan 4, 2009
    #14
  15. Hi Morris,

    To learn Silverlight you can refer to this page:

    http://silverlight.net/GetStarted/

    We need to install Silverlight Tools for Visual Studio first.

    If you don't want to use RIA technique I think we have to do the check
    after uploading, as mentioned in one of my previous posts:

    Aspx:
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="Button1" runat="server"
    Text="Upload" onclick="Button1_Click" />

    Aspx.cs:
    protected void Button1_Click(object sender, EventArgs e)
    {
    bool _ismono = false;
    int _samplerate = 0;
    int _bitspersample = 0;
    byte[] filebytes= this.FileUpload1.FileBytes;
    if (filebytes.Length >
    44&&this.FileUpload1.FileName.ToLower().EndsWith(".wav"))
    {
    _ismono = filebytes[22] == 1 && filebytes[23] == 0;
    byte[] samplerate = new byte[4] { filebytes[24],
    filebytes[25], filebytes[26], filebytes[27] };
    _samplerate = BitConverter.ToInt32(samplerate, 0);
    byte[] bitspersample = new byte[2] { filebytes[34],
    filebytes[35] };
    _bitspersample = BitConverter.ToInt16(bitspersample, 0);
    }
    }


    We can also use RegularExpressionValidator control directly:

    <asp:RegularExpressionValidator ControlToValidate="FileUpload1"
    ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.[wW][aA][v
    V])$" ID="RegularExpressionValidator1" runat="server" ErrorMessage="Only
    wav file can be uploaded!">
    </asp:RegularExpressionValidator>

    <asp:FileUpload ID="FileUpload1" runat="server"/>
    <asp:Button
    ID="Button1" runat="server" Text="Button" />

    In this way we can check the extension but cannot check the content of the
    wav file at client side.

    Please feel free to let me know if you have further questions.

    Regards,
    Allen Chen
    Microsoft Online Support
     
    Allen Chen [MSFT], Jan 5, 2009
    #15
  16. Hi Morris,

    Do you have additional questions on this issue?

    Regards,
    Allen Chen
    Microsoft Online Community Support
     
    Allen Chen [MSFT], Jan 13, 2009
    #16
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.