1

我根据放入文本框中的数字数据并单击按钮,使用以下代码填充 GridView。但它给出了以下错误。将数据类型 varchar 转换为浮点数时出错。由于我的数据库列“matri_perct”的数据类型为“float”。

protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL Connection String"].ConnectionString);con.Open();
        com = new SqlCommand("SELECT * FROM stdtable WHERE matri_perct >  @Percent", con);
        com.Parameters.AddWithValue("Percent", float.Parse(txtPercent.Text));
        com.ExecuteNonQuery();
            SqlDataAdapter dataadapter = new SqlDataAdapter();
            DataSet ds = new DataSet();
            dataadapter.Fill(ds, "Data");
            GridView1.DataSource = ds;
            GridView1.DataMember = "Data";
            con.Close();
        }
        catch (System.Exception err)
        {
            Label1.Text = err.Message.ToString();
        }
    }

我的 GridView .aspx 代码声明为

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="univ_regno" DataSourceID="" EnableModelValidation="True">
    <Columns>
        <asp:BoundField DataField="school" HeaderText="School" 
            SortExpression="school" />
        <asp:BoundField DataField="univ_regno" HeaderText="Univ R.No." ReadOnly="True" 
            SortExpression="univ_regno" />
        <asp:BoundField DataField="colge_rollno" HeaderText="Coll. R.No." 
            SortExpression="colge_rollno" />
        <asp:BoundField DataField="branch" HeaderText="Branch" 
            SortExpression="branch" />
        <asp:BoundField DataField="sem" HeaderText="Sem" SortExpression="sem" />
        <asp:BoundField DataField="name" HeaderText="Name" SortExpression="name" />
        <asp:BoundField DataField="f_name" HeaderText="F.Name" 
            SortExpression="f_name" />
        <asp:BoundField DataField="date_birth" HeaderText="DOB" 
            SortExpression="date_birth" />

        <asp:BoundField DataField="mob" HeaderText="Mobile" 
            SortExpression="mob" />
        <asp:BoundField DataField="email" HeaderText="E-mail" SortExpression="email" />
        <asp:BoundField DataField="matri_perct" HeaderText="Matric %" 
            SortExpression="matri_perct" />
        <asp:BoundField DataField="intermed_perct" HeaderText="Intermediate %" 
            SortExpression="intermed_perct" />
        <asp:BoundField DataField="grad_perct" HeaderText="UG %" 
            SortExpression="grad_perct" />
        <asp:BoundField DataField="post_grad_perct" HeaderText="PG %" 
            SortExpression="post_grad_perct" />
        <asp:BoundField DataField="other_perct" HeaderText="Other %" 
            SortExpression="other_perct" />
        <asp:BoundField DataField="no_backlogs" HeaderText="Backlogs" 
            SortExpression="no_backlogs" />
        <asp:BoundField DataField="Password" HeaderText="Password" 
            SortExpression="Password" />
    </Columns>
</asp:GridView>
  <asp:SqlDataSource ID="studentprofile" runat="server" 
        ConnectionString="<%$ ConnectionStrings:SQL Connection String %>" 

        SelectCommand="SELECT DISTINCT [school], [univ_regno], [colge_rollno], [branch], [sem], [name], [f_name], [date_birth], [cores_add], [mob], [email], [matri_perct], [intermed_perct], [grad_perct], [post_grad_perct], [other_perct], [no_backlogs], [Password] FROM [stdtable] ORDER BY [branch], [univ_regno]">
    </asp:SqlDataSource>
4

3 回答 3

3

首先,养成使用参数构造 SQL 语句的习惯,就像在 rene 的回答中一样,而不是通过连接。通过这种方式,您将避免很多问题(例如,SQL 注入攻击、带有转义字符的字符串会破坏 SQL 语句)。

其次,如果matri_perct是浮点数,正确的语法是:

com = new SqlCommand("SELECT * FROM stdtable WHERE matri_perct > " + 
    float.Parse(txtPercent.Text) + ", con);

没有单引号或百分号。

正如我所说,不要将其直接复制到您的生产代码中!,而是将用户输入转换为参数。考虑如果用户输入会发生什么

0); DROP TABLE Students; --

进入你的文本框。

编辑

这段代码让我有点困惑:

com.ExecuteNonQuery();  // looks like you're running the SELECT statement then discarding the result
SqlDataAdapter dataadapter = new SqlDataAdapter();
DataSet ds = new DataSet();
dataadapter.Fill(ds, "Data");  // I don't see how this gets the data from your query, above.
GridView1.DataSource = ds;
GridView1.DataMember = "Data";  // see my change, below.

这个怎么样(保持你的前三行不变):

SqlDataReader reader = com.ExecuteReader();  // execute SELECT statement, store result in data reader
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.Fill( reader );
GridView1.DataSource = adapter;
GridView1.DataBind();
于 2012-11-04T12:14:42.747 回答
2

让 sqlclient 完成繁重的工作:

    com = new SqlCommand("SELECT * FROM stdtable WHERE matri_perct >  @percent", con);
    com.Parameters.AddWithValue("percent", float.Parse(txtPercent.Text));
    com.ExecuteNonQuery();

或者,如果您想更具体地了解sqlparameter 类型

com = new SqlCommand("SELECT * FROM stdtable WHERE matri_perct >  @percent", con);
var percentParam = new SqlParameter("percent", SqlDbType.Float);
percentParam.Value = txtPercent.Text;
com.Parameters.Add(percentParam);

最重要的是:始终使用参数(如 Bob 所指出的)而不是字符串连接,否则您会在此过程中遇到麻烦。

于 2012-11-04T12:17:01.890 回答
2

我在@Bob Kaufman 和@rene 的帮助下解决了我的问题我的问题的完整解决方案如下:

protected void Button1_Click(object sender, EventArgs e)
{
    try
    {

        con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL Connection String"].ConnectionString);
        con.Open();
        com = new SqlCommand("SELECT * FROM stdtable WHERE matri_perct >  @Percent", con);
        com.Parameters.AddWithValue("@Percent", float.Parse(txtPercent.Text));
        SqlDataReader reader = com.ExecuteReader();  // execute SELECT statement, store result in data reader
        GridView1.DataSource = reader;
        GridView1.DataBind();
        con.Close();
         }
    catch (System.Exception err)
    {
        Label1.Text = err.Message.ToString();
    }
}

然后我改变了 AllowPaging=false

有用 ;)

于 2012-11-04T15:00:28.917 回答