将 SQLDataReader 与 SQLDataSource 和控件一起使用页面上的值

发布于 2024-11-29 06:05:41 字数 4078 浏览 0 评论 0原文

我有一个搜索引擎,它使用 ASP.NET 中的 SqlDataSource 控件,该控件从带有参数的存储过程中获取数据。我从页面上的默认值和控件中获取参数,这样用户就可以得到他想要的东西。然后该数据显示在 GridView 控件中。

现在,我必须添加一个导出按钮,它将结果导出到 Excel 文档中以供用户下载。我不确定这是否是最好的方法,但我使用了微软的算法(http://support.microsoft.com/default.aspx?scid=kb;en-us;308247) 来执行此操作。当我尝试获取搜索字段的值时出现了问题。你看,我们将使用它作为模板,因为我们有大约十几个搜索引擎要制作,并且我们希望有一些可以动态工作的东西。

下面是 aspx 页面上的 SqlDataSource 控件的示例:

<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>

下面是导出代码:

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;
        */
    }

由于它需要是动态的,因此导出代码需要能够工作无论中使用什么SqlDataSource 控件。因此,如果它有更多参数、不同的连接字符串或类似的东西,它仍然需要工作。我们不必更改不同引擎的代码。

所以问题是:如何获取 SqlDataSource SearchDataSource 使用的控件的值作为 C# 用户定义方法中 SqlDataReader dr 的参数< code>void exportExcel() 链接到我的 aspx 页面而不对控件的 ID 进行硬编码?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梅倚清风 2024-12-06 06:05:41

像这样的东西应该可以工作:

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

您可能也想在这里执行并检查 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;
}

要获取使用 Evaluate 方法评估 ControlParameter 对象所需的值: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.controlparameter.evaluate.aspx

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文