简体   繁体   English

GridView和SqlDataSource

[英]GridView and SqlDataSource

Im trying to create my own command to extract data. 我试图创建自己的命令来提取数据。 First im make in .aspx from toolbox SqlDataSource : 首先从工具箱SqlDataSource在.aspx中进行即时生成:

 <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        onselecting="SqlDataSource2_Selecting"></asp:SqlDataSource>

Then add GridView: 然后添加GridView:

 <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        onselecting="SqlDataSource1_Selecting"></asp:SqlDataSource>

and now I want to write my own query so I doubleclick on "SqlDataSource" >go into .aspx.cs: 现在我想编写自己的查询,所以我双击“ SqlDataSource”>进入.aspx.cs:

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)    
{
    SqlDataSource1.SelectCommand = "SELECT name, num  FROM Table WHERE T_Name=@MyString";
}

Where is the problem ? 问题出在哪儿 ? When I run this app is not working. 当我运行该应用程序时无法正常工作。

you didn't set the parameters for SqlDataSource1 . 您没有设置SqlDataSource1的参数。
and i cant the connection string. 我不能连接字符串。

There are a few problems. 有一些问题。 First one is you have used a parameterized query but haven't define what your parameter is. 第一个是您使用了参数化查询,但尚未定义参数是什么。 Second one is you just assign an SQL query to your SqlDataSource1 but you haven't say that to do with that. 第二个是您只是向您的SqlDataSource1分配了一个SQL查询,但您并没有为此说过话。

protected void Page_Load(object sender, EventArgs e)
{
    System.Data.Sql.SqlConnection conn= new System.Data.Sql.SqlConnection(/*your connection string comes here*/);

    string query= "SELECT name, num  FROM Table WHERE T_Name=@MyString";

    System.Data.DataTable dt = new System.Data.DataTable();
    System.Data.Sql.SqlCommand cmd = new System.Data.Sql.SqlCommand(query, conn);

    System.Data.Sql.SqlDataAdapter da1 = new System.Data.Sql.SqlDataAdapter(cmd );
    da1.SelectCommand.Parameters.AddWithValue("@MyString", your_string);

    da1.Fill(dt);

        if (dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }

You should add select parameters with the select command 您应该使用select命令添加选择参数

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
        {
            SqlDataSource1.SelectCommand = "SELECT name, num  FROM Table WHERE T_Name=@MyString";
SelectParameters["MyString"].DefaultValue = "Your Parameter here";

        }

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

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