I have a search engine that uses a SqlDataSource control in ASP.NET which gets data from a stored procedure with parameters. I get the parameters from default values and controls on the page, so the user can get what he wants. That data is then shown in a GridView control.

Now, I have to add an export button, which will export the results in an excel document to be downloaded by the user. I'm not sure if it is the best way, but I used the algorithm from microsoft (http://support.microsoft.com/default.aspx?scid=kb;en-us;308247) to do this. The problem arose when I tried getting the values of the search fields. You see, we'll use this as a template, since we have about a dozen search engines to make, and we'd like to have something that works dynamically.

Here's an exemple of the SqlDataSource control on the aspx page :

<asp:SqlDataSource ID="SearchDataSource" runat="server"
    ConnectionString="CONNECTIONSTRING"
    ProviderName="System.Data.SqlClient"
    SelectCommand="sp_SearchEngine_BASE" 
    SelectCommandType="StoredProcedure" onselected="SearchDataSource_Selected">
    <SelectParameters>
        <asp:ControlParameter ControlID="ctlID1" DbType="SomeType" DefaultValue="" 
            Name="spParamA" PropertyName="aProperty" />
        <asp:ControlParameter ControlID="ctlID2" DbType="SomeType" DefaultValue="" 
            Name="spParamB" PropertyName="aProperty" />
    </SelectParameters>
</asp:SqlDataSource>

And here's the exportation code :

protected void exportExcel()
    {
        int i;
        String strLine = "", filePath, fileName, fileExcel;
        FileStream objFileStream;
        StreamWriter objStreamWriter;
        Random nRandom = new Random(DateTime.Now.Millisecond);
        //Dim fs As Object, myFile As Object
        SqlConnection cnn = new SqlConnection(SearchDataSource.ConnectionString);

        //Create a pseudo-random file name.
        fileExcel = "t" + nRandom.Next().ToString() + ".xls";

        //Set a virtual folder to save the file.
        //Make sure that you change the application name to match your folder.
        filePath = Server.MapPath("\\ExcelTest");
        fileName = filePath + "\\" + fileExcel;

        //Use FileStream to create the .xls file.
        objFileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
        objStreamWriter = new StreamWriter(objFileStream);

        //Use a DataReader to connect to the Pubs database.
        cnn.Open();
        String sql  = SearchDataSource.SelectCommand;
        SqlCommand cmd = new SqlCommand(sql, cnn);

        //cmd.Parameters.Add(SearchDataSource.SelectParameters[0].);
        for (i = 0; i <= SearchDataSource.SelectParameters.Count - 1; i++)
        {
            // ---------------------------------------
            // ----- Here is where I am stuck... -----
            // ---------------------------------------
            //cmd.Parameters.AddWithValue(SearchDataSource.SelectParameters[i].Name, WhatDoIPutHere);
        }

        SqlDataReader dr;
        dr = cmd.ExecuteReader();

        //Enumerate the field names and records that are used to build the file.
        for(i = 0; i <= dr.FieldCount - 1; i++) {
           strLine = strLine + dr.GetName(i).ToString() + "\t";
        }

        //Write the field name information to file.
        objStreamWriter.WriteLine(strLine);

        //Reinitialize the string for data.
        strLine = "";

        //Enumerate the database that is used to populate the file.
        while (dr.Read()) {
           for(i = 0; i<= dr.FieldCount - 1; i++) {
              strLine = strLine + dr.GetValue(i) + "\t";
           }

           objStreamWriter.WriteLine(strLine);
           strLine = "";
        }

        //Clean up.
        dr.Close();
        cnn.Close();
        objStreamWriter.Close();
        objFileStream.Close();
        /*
        //Show a link to the Excel file.
        HyperLink1.Text = "Open Excel";
        HyperLink1.NavigateUrl = fileExcel;
        */
    }

Since it needs to be dynamic, the exportation code needs to works whatever is used in the SqlDataSource control. So if it has more parameters, a different connection string or anything like that, it still needs to work. We shouldn't have to change to code for a different engine.

So here's the question : How can I get the values of the controls used by the SqlDataSource SearchDataSource as parameters for the SqlDataReader dr in the C# user-defined method void exportExcel() linked to my aspx page without hard-coding the controls' IDs?

share|improve this question

1 Answer

Something like this should work:

for(int i = 0; i < SearcDataSource.SelectParameters.Count; i++)
{
   string controlId= (ControlParameter)SearchDataSource.SelectParameters[i].ControlID;
}

You may wanna do an as here too and check for null:

for(int i = 0; i < SearcDataSource.SelectParameters.Count; i++)
{
   var controlParam = SearchDataSource.SelectParameters[i] as ControlParameter;
   if (controlParam == null) continue;
   string controlId= controlParam.ControlID;
}

To get the value you need to evaluate the ControlParameter object using the Evaluate method: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.controlparameter.evaluate.aspx

share|improve this answer
I think you're missing a part of the question : How can I get it's value? – JMichelB Aug 11 '11 at 15:52
To get the value you need to evaluate the ControlParameter object using the Evaluate method: msdn.microsoft.com/en-us/library/… – Josh Aug 11 '11 at 16:28
I can't find a way to use Evaluate! MSDN doesn't give an exemple and VS can't help either... You updated to give the link, why didn't you updated your example too? – JMichelB Aug 11 '11 at 17:31
Because I don't agree with doing your work for you. You have enough above to figure it out if you Googled. You find your control id using the for loop above. From that, you can find the control object in your page. You send the control object to Evaluate with the HTTPContext of your page. Evaluate will then return the value. – Josh Aug 11 '11 at 17:52
I'm ok with you not wanting to do my job, but you aren't helping me at all. I searched over 10 pages of google and check a couple of tens of websites, and none with even an exemple of the use of Evaluate. My problem is still present : I can't find a way to get the controls' values. – JMichelB Aug 11 '11 at 18:12

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.