将变量传递给SqlDataSource.SelectParameter,然后将查询结果传递给新的字符串ASP.NET

时间:2018-04-12 15:10:44

标签: c# asp.net sqldatareader sqldatasource

我将以下SqlDataSource定义为DataReader,其默认值为空白:

<asp:SqlDataSource ID="getPhoneNumber" runat="server" ConnectionString="<%$ ConnectionStrings:MobileLeasesConnectionString %>" DataSourceMode="DataReader" SelectCommand="SELECT Phone FROM MobileLeases WHERE OwnerName = @techName">
        <SelectParameters>
            <asp:Parameter Name="techName" Type="string" />
        </SelectParameters>
    </asp:SqlDataSource>

我有一个按钮点击事件,可以在点击按钮时抓取表单字段的值,并将其放入string techName ...

protected void submitter_Click(object sender, EventArgs e)
{        
    //grab the value of ftechName at the time the button is clicked...        
    string techName = Request.Form["ftechName"]; //grab the techs name}

我需要将techName的值传递给getPhoneNumber ...并将单个结果返回给新字符串,将其称为字符串phoneNum

我已经尝试了几件事,只需要从头开始建议,因为它现在都很模糊。

大图,看起来应该是这样......

protected void submitter_Click(object sender, EventArgs e)
{        
    //grab the value of ftechName at the time the button is clicked...        
    string techName = Request.Form["ftechName"]; //grab the techs name}

    //run select command with techName as the SELECT parameter...
    getPhoneNumber > Select Phone WHERE OwnerName = techName
    string phoneNum = result of getPhoneNumber query

传递techName并将结果转换为phoneNum的最佳方法是什么?

非常感谢您的任何建议。

1 个答案:

答案 0 :(得分:0)

不确定,因为我没有使用太多的ASP.NET:

getPhoneNumber.SelectParameters.Add("@techName", System.Data.DbType.String, techName);

**更新:**

以下是我编写的一些没有asp:SqlDataSource控件的代码:

protected void Submit_Clicked(object sender, EventArgs e)
{
    var techName = ftechName.Text.Trim();
    // assuming your phone number control on your ASP.NET page is "rPhonenumber"
    rPhonenumber.Text = GetPhoneNumber(techName);
}

private const String SQL_CONNECTION = "ConnectionStrings:MobileLeasesConnectionString";

private String GetPhoneNumber(String techName)
{
    var result = String.Empty;
    using (var con = new System.Data.SqlClient.SqlConnection(SQL_CONNECTION))
    {
        // Give it your SQL command
        var sql = "SELECT Phone FROM MobileLeases WHERE OwnerName = @techName";
        // Create an SqlCommand instance
        var cmd = new System.Data.SqlClient.SqlCommand(sql, con);
        // Supply it with your parameter (data type and size should match whatever the value is for [MobileLeases].[OwnerName] in SQL)
        cmd.Parameters.Add("@techName", System.Data.SqlDbType.VarChar, 40).Value = techName;
        // Don't forget to open the connection!
        cmd.Connection.Open();
        // String.Format handles the case of the SELECT command returning NULL - converting that to an empty string
        result = String.Format("{0}", cmd.ExecuteScalar());
        // optionally, you can close the connection, but the 'using' statement should take care of that.
        cmd.Connection.Close();
    }
    // return your results
    return result;
}

在我看来,更容易理解发生了什么。

相关问题