问一个简单的问题,在这道程序里面
string goodsName = this.GridView1.DataKeys[e.RowIndex][0].ToString();
string  salePrice = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString();
string discount = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString();
salePrice discount对应的数据库 类型是numeric ,但我在这里不知道应该怎么把string去把它转换为数据库所需要的numeric 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;namespace WebTest
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {        }        public void getData()
        {
            SqlConnection cn = new SqlConnection("server=localhost;database=student;user=xie;password=xie");
            SqlCommand cmd = new SqlCommand("select*from goods", cn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "goods");
            this.GridView1.DataSource = ds.Tables[0].DefaultView;
            this.DataBind();
        }        protected void Button1_Click(object sender, EventArgs e)
        {
            getData();
        }        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.GridView1.PageIndex = e.NewPageIndex;
            getData();
        }        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {        }
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {        }        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.GridView1.EditIndex = e.NewEditIndex;
            getData();
        }        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string goodsName = this.GridView1.DataKeys[e.RowIndex][0].ToString();
            string  salePrice = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString();
            string discount = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString();
            Response.Write("afdasfd");
            updataGoods(goodsName,salePrice ,discount);
            this.GridView1.EditIndex = -1;
            getData();
        }        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.GridView1.EditIndex = -1;
            getData();
        }
        public void updataGoods(string goodsName,string  salePrice, string   discount)
        {
            SqlConnection cn = new SqlConnection("server=localhost;database=student;user=xie;password=xie");
            SqlCommand cmd = new SqlCommand("update goods set goodsName=' " +goodsName+" ', salePrice=' " +salePrice+" ', discount=' " +discount+" ' where goodsName=' "+goodsName+" ' ", cn);
            cn.Open();
            cmd.ExecuteNonQuery();
            cn.Close();
        }
    }
}

解决方案 »

  1.   

    不用转换,就按string传递即可,在拼sql时拼出合法的sql即可
    你的拼法不对,数字类型不应该有单引号,正确写法是:
    SqlCommand cmd = new SqlCommand("update goods set goodsName='" +goodsName+ "', salePrice=" +
        salePrice+ ", discount=" +discount+ " where goodsName='" +goodsName+ "' ", cn);
    另外这种拼sql的方法是不好的,上面的写法是典型的sql注入漏洞,应该用传参方法
    SqlCommand cmd = new SqlCommand("update goods set goodsName=@goodsName, salePrice=@salePrice, discount=@discount where goodsName=@goodsName", cn);
    cmd.Parameters.Add(new SqlParameter("goodsName", goodsName));
    cmd.Parameters.Add(new SqlParameter("salePrice", double.Parse(salePrice)));
    cmd.Parameters.Add(new SqlParameter("discount", double.Parse(discount)));
      

  2.   

    还是不行喔!!
    不知道为什么!!
    在cmd.Parameters.Add(new SqlParameter("salePrice", double.Parse(salePrice)));
    cmd.Parameters.Add(new SqlParameter("discount", double.Parse(discount)));
     说 {"输入字符串的格式不正确。"}
      

  3.   

    你看看你的这两个是什么值
    cmd.Parameters.Add(new SqlParameter("salePrice", double.Parse(salePrice)));
    cmd.Parameters.Add(new SqlParameter("discount", double.Parse(discount))); 不要带字符,不然会报错的!!!
      

  4.   

    没有带字符呀,我里面都是数字 1.0 10.0 都是double的但是转换就报错了
    我一直在想会不会是下面这里写错了
     string goodsName = this.GridView1.DataKeys[e.RowIndex][0].ToString();
                string  salePrice = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString();
                string discount = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString();
                Response.Write("afdasfd");
                updataGoods(goodsName,salePrice ,discount);
      

  5.   

    还真没这么写过。
    cmd.Parameters.Add(new SqlParameter("discount", double.Parse(discount)));
    sqlparameter("discount",这里跟的是个类型sqldbType 而不是一个值)
      

  6.   

    类型??是 char 或者 numeric????
      

  7.   


    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebTest._Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        
            <asp:GridView ID="GridView1" runat="server" Width ="100%" CellPadding="4" 
                ForeColor="#333333" GridLines="None" 
                onselectedindexchanged="GridView1_SelectedIndexChanged" AllowPaging="True" 
                AutoGenerateColumns="False" DataKeyNames="goodsName,salePrice,discount" 
                onpageindexchanging="GridView1_PageIndexChanging" 
                onrowcancelingedit="GridView1_RowCancelingEdit" 
                onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
                onrowupdating="GridView1_RowUpdating" PageSize="5">
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <Columns>
                    <asp:BoundField DataField="goodsName" HeaderText="商品名称" />
                    <asp:BoundField DataField="salePrice" HeaderText="价格" />
                    <asp:BoundField DataField="discount" HeaderText="打折" />
                    <asp:CommandField ShowEditButton="True" />
                    <asp:CommandField ShowSelectButton="True" />
                    <asp:CommandField ShowDeleteButton="True" />
                </Columns>
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <EditRowStyle BackColor="#999999" />
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            </asp:GridView>
        
        </div>
        <asp:Button ID="Button1" runat="server" Height="29px" onclick="Button1_Click" 
            Text="Button" Width="149px" />
        </form>
    </body>
    </html>
      

  8.   

    没有看出有什么错误,你先把前台改下加上输入验证防止输错,像这样:
    <asp:TemplateField HeaderText="价格">
    <ItemTemplate><%# Eval(salePrice) %></ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox id="price" runat="server" Text='<%# Eval("salePrice") %>' />
    <asp:RegularExpressionValidator runat="server" ErrorMessage="价格必须是数字"
    ControlToValidate="price" Display="Dynamic" ValidationExpression="\d+(\.\d*)?" />
    </EditItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="打折">
    <ItemTemplate><%# Eval(discount) %></ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox id="discount" runat="server" Text='<%# Eval("discount") %>' />
    <asp:RegularExpressionValidator runat="server" ErrorMessage="折扣必须是数字"
    ControlToValidate="discount" Display="Dynamic" ValidationExpression="\d+(\.\d*)?" />
    </EditItemTemplate>
    </asp:TemplateField>
      

  9.   

    对了,我终于知道我这道程序什么问题了
    其他的都没有错,有错的是
    cmd.Parameters.Add(new SqlParameter("discount", double.Parse(discount))); 
    在这里我打折是可以为空的,也就是说如果没有打折的话就是为空。  它显示不能为无限大
    那么我想请教一下,如果为空的时候怎么输出呢!!!~~
    先谢谢了。
      

  10.   

    嗯,是我用了偷懒的方法,严谨的写法是
    SqlParameter p = new SqlParameter ("discount", SqlDbType.Decimal);
    p.Value = discount;
    cmd.Parametes.Add(p);
    这样就不会错了,不过要多写几行
      

  11.   

    不知道为什么这里还是有点问题
     string discount = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString();
    提示
    无法将类型为“System.Web.UI.WebControls.DataControlLinkButton”的对象强制转换为类型“System.Web.UI.WebControls.TextBox”。
    当从一个数字执行强制转换时,值必须是一个小于无限大的数字
      

  12.   

    再来
    SqlParameter p = new SqlParameter ("discount", SqlDbType.Decimal);
    p.Value = string.IsNullOrEmpty(discount)? 0 : discount;
    cmd.Parametes.Add(p);
      

  13.   

    刚才没注意看错误提示
    string discount = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString();
    Cells[3] <-- 这里为什么是3?第4个字段是编辑按钮啊!
      

  14.   

    我加了个主键 goodsId
    所以就是3了
    好像这里有问题
      

  15.   

    如果改为这个反而有误呀,
    C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\WebTest\WebTest\Default.aspx.cs(85,55): 错误 CS0173: 无法确定条件表达式的类型,因为“int”和“string”之间没有隐式转换
    我觉得是前面那一句的问题
    string discount = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString(); 
      

  16.   

    string discount = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[3].Controls
    编译过了,但是编辑信息的时候这里老出错,当从一个数字执行强制转换时,值必须是一个小于无限大的数字 
    我上网查了一下说string discount = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString(); 
    不能用于null 
    如果不行还有其他方法吗
      

  17.   

    goodsId 是可见的吗? 如果不可见那 discount 的cell索引还是2
      

  18.   

    参数化查询 '(@goodsId nvarchar(6),@goodsName nvarchar(5),@salePrice decimal(' 需要参数 '@salePrice',但未提供该参数。
    真的不大行。我发我的原代码上来好了,帮我看看。。
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;namespace WebTest
    {
        public partial class _Default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {        }        public void getData()
            {
                SqlConnection cn = new SqlConnection("server=localhost;database=student;user=xie;password=xie");
                SqlCommand cmd = new SqlCommand("select*from goods", cn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds, "goods");
                this.GridView1.DataSource = ds.Tables[0].DefaultView;
                this.DataBind();
            }        protected void Button1_Click(object sender, EventArgs e)
            {
                getData();
            }        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
            {
                this.GridView1.PageIndex = e.NewPageIndex;
                getData();
            }        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
            {        }
            protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
            {
                string goodsId = this.GridView1.DataKeys[e.RowIndex][0].ToString();
                daletegoods(goodsId);
                getData();
            }        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
            {
                this.GridView1.EditIndex = e.NewEditIndex;
                getData();
            }        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
            {
                string goodsId = this.GridView1.DataKeys[e.RowIndex][0].ToString();
                string goodsName = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text.ToString();
                string   salePrice = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString();
                string discount = ((TextBox)this.GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString();
                updataGoods(goodsId,goodsName,salePrice ,discount);
                this.GridView1.EditIndex = -1;
                getData();
            }        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
            {
                this.GridView1.EditIndex = -1;
                getData();
            }
            public void updataGoods(string goodsId,string goodsName,string  salePrice, string   discount)
            {
                SqlConnection cn = new SqlConnection("server=localhost;database=student;user=xie;password=xie");
               // SqlCommand cmd = new SqlCommand("update goods set goodsId="+goodsId+" ,goodsName="+goodsName+" , salePrice=" +salePrice+", discount=" +discount+" where goodsId="+goodsId+" ", cn);
                SqlCommand cmd = new SqlCommand("update goods set goodsId=@goodsId,goodsName=@goodsName,salePrice=@salePrice,discount=@discount where goodsId=@goodsId", cn);
                cmd.Parameters.Add(new SqlParameter("goodsId", goodsId));
                cmd.Parameters.Add(new SqlParameter("goodsName", goodsName));
                 cmd.Parameters.Add(new SqlParameter("salePrice",SqlDbType.Decimal));
              //  cmd.Parameters.Add(new SqlParameter("@discount", SqlDbType.Decimal));
                 SqlParameter p = new SqlParameter("discount",SqlDbType.Decimal);
                 p.Value = string.IsNullOrEmpty(discount)?"0":discount ;
                 cmd.Parameters.Add(p);
                cn.Open();  
                cmd.ExecuteNonQuery();
                cn.Close();
            }
            public void daletegoods(string goodsId)
            {
                SqlConnection cn = new SqlConnection("server=localhost;database=student;user=xie;password=xie");
                SqlCommand cmd = new SqlCommand("delete from goods where goodsId='" + goodsId + "'", cn);
                cn.Open();
                cmd.ExecuteNonQuery();
                cn.Close();
            }
        }
    }
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebTest._Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
    <head id="Head1" runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        
            <asp:GridView ID="GridView1" runat="server" Width ="100%" CellPadding="4" 
                ForeColor="#333333" GridLines="None" 
                onselectedindexchanged="GridView1_SelectedIndexChanged" AllowPaging="True" 
                AutoGenerateColumns="False" DataKeyNames="goodsId,goodsName,salePrice,discount" 
                onpageindexchanging="GridView1_PageIndexChanging" 
                onrowcancelingedit="GridView1_RowCancelingEdit" 
                onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
                onrowupdating="GridView1_RowUpdating" PageSize="5">
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                <Columns>
                    <asp:BoundField DataField="goodsName" HeaderText="商品名称" />
                    <asp:BoundField DataField="salePrice" HeaderText="价格" />
                    <asp:BoundField DataField="discount" HeaderText="打折" />
                    <asp:CommandField ShowEditButton="True" />
                    <asp:CommandField ShowSelectButton="True" />
                    <asp:CommandField ShowDeleteButton="True" />
                </Columns>
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <EditRowStyle BackColor="#999999" />
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            </asp:GridView>
        
        </div>
        <asp:Button ID="Button1" runat="server" Height="29px" onclick="Button1_Click" 
            Text="Button" Width="149px" />
        </form>
    </body>
    </html>
    BH0101 奇奇洗衣粉 百货 750g 奇奇 6.50 6.20
    BH0103 多多透明皂 百货 125g*4 多多 6.00 5.50
    BH0104 多多洗发露 百货 400ml 多多 30.00 NULL
    DQ0101 液晶数码电视机 电器 172*141*33 康佳 5000.00 NULL
    DQ0102 车载液晶电视机 电器 9英寸 康佳 800.00 NULL
    DQ0104 彩虹数码照相机 电器 500像素 彩虹 2000.00 NULL
    DQ0203 小小数码照相机 电器 300像素 小小 1800.00 NULL
    DQ0305 MP3播放器 电器 56*38*15 台电 100.00 NULL
    FZ0101 活力衬衣 纺织 42 老人头 80.00 60.00
    FZ0102 高贵西装 纺织 XXL 老人头 600.00 450.00
    FZ0203 奇胜衬衣 纺织 43 奇胜 70.00 NULL
    HZ0101 阳光活肤润白乳 化妆 100g 阳光 35.00 NULL
    HZ0102 阳光香水 化妆 30ml 阳光 20.00 NULL
    HZ0203 绿色植物沐浴露 化妆 500ml 强生 20.00 NULL
    HZ0204 男生香水 化妆 5ml 阳光 10.00 NULL
    HZ0305 月亮洗面奶 化妆 200g 佳雪 15.00 14.50
    SP0101 神怡咖啡 食品 13g 神怡 20.00 NULL
    SP0102 日日面包 食品 50g 日日 3.00 NULL
    SP0203 泡泡面包 食品 100g 泡泡 5.00 NULL
    NULL NULL NULL NULL NULL NULL NULL
      

  19.   

    SQL 
    SELECT TOP 1000 [goodsId]
          ,[goodsName]
          ,[goodsCategory]
          ,[specification]
          ,[producer]
          ,[salePrice]
          ,[discount]
      FROM [student].[dbo].[goods]
      

  20.   

    那后台  string goodsId = this.GridView1.DataKeys[e.RowIndex][0].ToString(); 
    这句话就是错的,根本取不到数据啊
      

  21.   

    仔细看了下你的代码,里面的错真不少,后台改成这样protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
    e.Cancel = true;
    string goodsId = (string)e.Keys[0];
    string goodsName = e.NewValues["goodsName"] as string;
    double salePrice, discount;
    double.TryParse(e.NewValues["salePrice"] as string, out salePrice);
    double.TryParse(e.NewValues["discount"] as string, out discount);
    updataGoods(goodsId, goodsName, salePrice, discount);
    this.GridView1.EditIndex = -1;
    getData();
    }前台 GridView的datakeynames改成goodsid:
     DataKeyNames="goodsId" 
      

  22.   

    可以了
    前台已经改了,不过还是不行
    后来我干脆把之前你给的关于discount为NULL的解决方法用在salePrice上,结果可以运行
    不过有点不明白的是,salePrice虽然为numeric 但是它在表里面并没有null,如果说有的话
    就是SQL最后面那一行全为 null null null ……的(这行用于插入的)
    不明白过中原因,难不成最后面的这些null 也算在表里面(可是网页上并没有显示啊)。
    下面是可以运行的代码。            SqlParameter q = new SqlParameter("salePrice",SqlDbType.Decimal);
                q.Value = string.IsNullOrEmpty(salePrice) ? "0" : discount;
                cmd.Parameters.Add(q);
                 SqlParameter p = new SqlParameter("discount",SqlDbType.Decimal);
                 p.Value = string.IsNullOrEmpty(discount)?"0":discount ;
                 cmd.Parameters.Add(p);