繁体   English   中英

如何使用C#在后面的代码中使用参数访问我的aspx文件中的某些控件

[英]how to use parameters in code behind to access some controls in my aspx file using C#

我有2个文本框,在我的aspx文件中有一个日期值。 我想使用后面的代码在我的select语句中访问这2个控件,但是我遇到了这样的错误:“必须声明标量变量“ @txtStartClosingDate”,所以我后面的代码在这里缺少什么? 谢谢

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            MainGridView.DataSource = GetData("select   GroupCategory, Count(Status1) as TotalCount from  [MasterProject] where Closing_Date >= @txtStartClosingDate and Closing_Date <= @txtEndClosingDate and Status1 is not null group by  GroupCategory");
            MainGridView.DataBind();


        }
    }

这是我要参考的文本框之一:

<asp:TextBox ID="txtStartClosingDate" runat="server" CssClass="datepicker"></asp:TextBox>

尽管我强烈建议您这样做(由于SQL注入漏洞),但我认为您想要做的是:

if (!IsPostBack)
{
    MainGridView.DataSource = GetData("select   GroupCategory, Count(Status1) as TotalCount from  [MasterProject] where Closing_Date >= '"+ txtStartClosingDate.Text +"' and Closing_Date <= '"+ txtEndClosingDate.Text +"' and Status1 is not null group by  GroupCategory");
    MainGridView.DataBind();
}

GetData方法是什么样的? 它是否需要任何SQL参数?

在aspx页面后面的代码中编写sql查询是错误的做法。 解决方案有很多,其中一种是使用3层结构的应用程序:GUI是aspx页面,业务逻辑层将处理应用程序的逻辑,数据访问层实际上将通过调用查询或存储过程与DB进行通信,实际上比仅在代码中编写查询要好。 为什么? 因为存储过程是在数据库中编译一次的,而不像每次都会编译的内联查询那样,所以您可以将变量传递给存储的priceure,这将有助于防止sql注入。

签出架构示例:

http://shoutingwords.com/creating-3-tier-layered-application-using-c-sharp.html

存储过程:

http://www.codeproject.com/Articles/38682/Overview-of-SQL-Server-Stored-Procedure

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM