这是我的 C# 代码:
protected void UpdateProduct(object sender, GridViewUpdateEventArgs e) // ⇦ Gridview products update event
{
string Tax = (GridViewProducts.Rows[e.RowIndex].FindControl("EditTaxDropDown") as DropDownList).SelectedItem.Value;
string Type = (GridViewProducts.Rows[e.RowIndex].FindControl("EditTypeDropDown") as DropDownList).SelectedItem.Value;
string Id = GridViewProducts.DataKeys[e.RowIndex].Value.ToString();
string Name = (GridViewProducts.Rows[e.RowIndex].FindControl("TBName") as TextBox).Text;
string Description = (GridViewProducts.Rows[e.RowIndex].FindControl("TBDescription") as TextBox).Text;
string Price = (GridViewProducts.Rows[e.RowIndex].FindControl("TBPrice") as TextBox).Text;
string SerialNumber = (GridViewProducts.Rows[e.RowIndex].FindControl("TBSerialNumber") as TextBox).Text;
string strConnString = ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
string query = "UPDATE Products SET Name = @Name, Description = @Description, Price = @Price, type = @type, Tax = @Tax, SerialNumber = @SerialNumber, Meta_Modified = GETDATE() WHERE Id = @Id";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Id", Id);
cmd.Parameters.AddWithValue("@Tax", Tax);
cmd.Parameters.AddWithValue("@Name", Name);
cmd.Parameters.AddWithValue("@Description", Description);
cmd.Parameters.AddWithValue("@Type", Type);
cmd.Parameters.Add("@Price", SqlDbType.Int, 50).Value = Convert.ToInt32(Price);
cmd.Parameters.AddWithValue("@SerialNumber", SerialNumber);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridViewProducts.EditIndex = -1;
BindGridData();
ProductGWBindData(); //refreshes gridview
}
}
}
这是 HTML 标记:
<asp:TemplateField HeaderText="Price" SortExpression="Price" >
<ItemTemplate>
<asp:Label ID="TBPrice" runat="server" Text='<%# Eval("Price", "{0:C2}")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox TextMode="Number" step="0.01" ID="TBPrice" runat="server" Text='<%# Eval("Price")%>' ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>`
如您所见,Price
由于某种原因,我对value感兴趣,我不知道如何将 string 转换为 int,我认为这与十进制“step=0.01”有关,我可以传递整数,例如 1、2、3 ... 但不是十进制格式 1.00 , 2.00 , 3.01 ...
请帮助我尝试将各种字符串转换为 int :(
将 db 类型更改为十进制,并将您的价格声明为十进制而不是字符串。我认为您的问题出在此代码上:
string Price = (GridViewProducts.Rows[e.RowIndex].FindControl("TBPrice") as TextBox).Text
更改为:
decimal Price = Convert.ToDecimal((GridViewProducts.Rows[e.RowIndex].FindControl("TBPrice") as TextBox).Text, new CultureInfo("en-US"));
你的命令参数应该是这样的:
cmd.Parameters.Add("@Price", Price);
我还没有测试这段代码,但我认为解决方案与此有些相似,如果我错了,请纠正我,希望它有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句