1

テキストボックスに入力された数値データに基づいて、GridViewに次のコードを入力し、ボタンをクリックします。しかし、それは次のエラーを与えています。データ型varcharをfloatに変換中にエラーが発生しました。私のデータベース列'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

まず、連結ではなく、reneの回答のように、パラメーターを使用してSQLステートメントを作成する習慣を身に付けます。この方法で、多くの問題(SQLインジェクション攻撃、SQLステートメントを壊すエスケープ文字を含む文字列など)を回避できます。

次に、matri_perctがfloatの場合、正しい構文は次のようになります。

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.

代わりにこれはどうですか(最初の3行はそのままにしておきます):

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

@ 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 に答える
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 に答える