错误:将nvarchar值转换为数据类型int时转换失败 [英] Error: Conversion failed when converting the nvarchar value to data type int

查看:76
本文介绍了错误:将nvarchar值转换为数据类型int时转换失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hello friends,im getting,listView中的itemtemplate值,并使用这些值插入数据库,

im得到错误:

错误:将nvarchar值转换为数据类型int时转换失败

请帮我恢复此错误。

我的代码是:

  protected   void  btn_add_Click( object  sender,EventArgs e)
{
Control c = sender as Control;
Label lbl =((Label)c.Parent.FindControl( subitem_nameLabel)) ;
标签lbl2 =((标签)c.Parent.FindControl( item_descriptLabel)) ;
标签lbl3 =((标签)c.Parent.FindControl( item_rateLabel)) ;
/ * foreach(ListView1.Items中的ListViewItem项)
{
Label lb =(Label)item.FindControl(subitem_nameLabel);
Label4.Text = lb.Text;
} * /

}


受保护 void ListView1_SelectedIndexChanged( object sender,EventArgs e)
{
cnn.ConnectionString = ConfigurationManager.ConnectionStrings [ jin]。ConnectionString;
控制c =发件人作为控件;
Label lbl =((Label)c.Parent.FindControl( subitem_nameLabel)) ;
标签lbl2 =((标签)c.Parent.FindControl( item_descriptLabel)) ;
标签lbl3 =((标签)c.Parent.FindControl( item_rateLabel)) ;
会话[ subitem_name] = lbl.Text;
会话[ item_descript] = lbl2.Text;
会话[ item_rate] = lbl3.Text;

尝试
{
cnn.Open();
SqlCommand cm = new SqlCommand( str_order ,cnn);
cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.Add( @ subitem_name,会话[ subitem_name]);
cm.Parameters.Add( @ item_descript,会话[ item_descript]);
cm.Parameters.Add( @ item_rate,会话[ item_rate]。ToString());
cm.ExecuteNonQuery();
Response.Write( < script>('Items Added')< / script>);
cnn.Close();
}
catch (例外情况)
{
// Response.Write(< script>('添加这些项时出错')< / script>);
回复于(ex.Message);

}


}





我的源代码是:

 <   asp:ListView     ID   =  ListView1    runat   = 服务器    DataKeyNames   =  itemname    

DataSourceID = SqlDataSource1

>


< EmptyDataTemplate >
未返回任何数据。
< / EmptyDataTemplate >

< ItemSeparatorTemplate >
< br / >
< / ItemSeparatorTemplate >
< ItemTemplate >
< li 样式 = background-color:#DCDCDC;颜色:#000000; > 子项名称:
< < span class =code-leadattribute> asp:Label ID = subitem_nameLabel runat = server

文字 =' <% #Eval( subit em_name)%>' / >
< br / >
项目描述:
< asp:标签 ID = item_descriptLabel runat = 服务器

文本 =' < % #Eval( item_descript)%>' / >
< br / >
项目费率:
< asp:标签 ID = item_rateLabel runat = server 文字 < span class =code-keyword> =' <% #Eval( item_rate)%>' < span class =code-keyword> / >
< br / >
< asp:按钮 ID = btn_add runat = server 文字 = 添加 CommandName = 选择 OnClick = ListView1_SelectedIndexChanged / >
< / li >
< / ItemTemplate >
< LayoutTemplate >
< ul ID = itemPlaceholderContainer runat = server

style < span class =code-keyword> = font-family:Verd ana,Arial,Helvetica,sans-serif; >
< li runat = server id = itemPlaceholder / >

< br / >
< / li >
< / ul >
< div style = text-align:center; background-color:#CCCCCC; font-family:Verdana,Arial,Helvetica,sans-serif; color:#000000; >
< / div >
< / LayoutTemplate >

< / asp:ListView >





i更改了我的代码:

  protected   void  ListView1_SelectedIndexChanged( object  sender,EventArgs e)
{
cnn.ConnectionString = ConfigurationManager.ConnectionStrings [ jin]。ConnectionString;
控制c =发件人作为控件;
Label lbl =((Label)c.Parent.FindControl( subitem_nameLabel)) ;
标签lbl2 =((标签)c.Parent.FindControl( item_descriptLabel)) ;
标签lbl3 =((标签)c.Parent.FindControl( item_rateLabel)) ;
会话[ subitem_name] = lbl.Text;
会话[ item_descript] = lbl2.Text;
decimal item_rate = Convert.ToDecimal(lbl3.Text);
会话[ item_rate] = item_rate;

尝试
{
cnn.Open();
SqlCommand cm = new SqlCommand( str_order ,cnn);
cm.CommandType = CommandType.StoredProcedure;
cm.Parameters.AddWithValue( @ subitem_name,会话[ subitem_name]);
cm.Parameters.AddWithValue( @ item_descript,会话[ item_descript]);
cm.Parameters.AddWithValue( @ item_rate,会话[ item_rate]。ToString());
cm.ExecuteNonQuery();
Response.Write( < script>('Items Added')< / script>< /跨度>);
cnn.Close();
}
catch (例外情况)
{
// Response.Write(< script>('添加这些项时出错')< / script>);
回复于(ex.Message);

}


}



我仍​​然收到错误:

将nvarchar值''asdd''转换为数据类型int时转换失败。

解决方案

试试这个:



标签lbl3 =((标签)c.Parent.FindControl(item_rateLabel)); 
Session [subitem_name] = lbl.Text;
Session [item_descript] = lbl2.Text;
decimal item_rate = Convert.ToDecimal(lbl3.text);
Session [item_rate] = item_rate;


 USE [JIN] 
GO
/ ******对象:StoredProcedure [dbo]。[str_order]脚本日期:03/13/2013 22:17:04 ****** /
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER程序[dbo]。[str_order]
@subitem_name nvarchar(50),
@item_descript nvarchar(100),
@item_rate decimal(18,2)
as
begin
declare @entrydate date
set @ entrydate = GETDATE()
declare @time time
set @time = CURRENT_TIMESTAMP
声明@order_id nvarchar(50)
set @ order_id = @ subitem_name + convert(nvarchar(50),DAY(getdate()))
插入Jin_order(subitem_name, item_descript,item_rate,entrydate,time,order_id)值(@ subitem_name,@ item_descript,@ item_rate,@ entrydate,@ time,@ order_id)
end







在SQL服务器上尝试上面的存储过程。



然后执行以下语句。



 exec str_order''asdd'',''test'',10.2 


SQL数据类型NVARCHAR是由ADO映射的可变长度Unicode字符串.NET直接到.NET类 System.String 。但当然不是数字类型。您可以进一步尝试使用 int.TryParse int.Parse将字符串解释为 int (如果字符串未被解析为整数,则可以抛出异常)。



但是这种情况应该会让你考虑你的数据库模式。您可能正在尝试使用表示数据的字符串而不是数据本身。这真的非常糟糕。如果相应列包含表示整数值的字符串,则应检查数据库模式并使用SQL整数类型之一而不是字符串。



-SA

hello friends, i m getting, values from itemtemplate in listView, and, using those values, to insert in database,
i m getting the error:
Error: Conversion failed when converting the nvarchar value to data type int
please help me to recover this error.
My code is:

protected void btn_add_Click(object sender, EventArgs e)
    {
        Control c = sender as Control;
        Label lbl = ((Label)c.Parent.FindControl("subitem_nameLabel"));
        Label lbl2 = ((Label)c.Parent.FindControl("item_descriptLabel"));
        Label lbl3 = ((Label)c.Parent.FindControl("item_rateLabel"));
        /*foreach (ListViewItem item in ListView1.Items)
        {
            Label lb = (Label)item.FindControl("subitem_nameLabel");
            Label4.Text = lb.Text;
        }*/
    }


    protected void ListView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        cnn.ConnectionString = ConfigurationManager.ConnectionStrings["jin"].ConnectionString;
        Control c = sender as Control;
        Label lbl =((Label)c.Parent.FindControl("subitem_nameLabel"));
        Label lbl2=((Label)c.Parent.FindControl("item_descriptLabel"));
        Label lbl3 = ((Label)c.Parent.FindControl("item_rateLabel"));
        Session["subitem_name"]= lbl.Text;
        Session["item_descript"] = lbl2.Text;
        Session["item_rate"] = lbl3.Text;

        try
        {
            cnn.Open();
            SqlCommand cm = new SqlCommand("str_order", cnn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.Add("@subitem_name", Session["subitem_name"]);
            cm.Parameters.Add("@item_descript", Session["item_descript"]);
            cm.Parameters.Add("@item_rate", Session["item_rate"].ToString());
            cm.ExecuteNonQuery();
            Response.Write("<script>('Items Added')</script>");
            cnn.Close();
        }
        catch (Exception ex)
        {
            //Response.Write("<script>('There is an Error while adding these Items')</script>");
            Response.Write(ex.Message);

        }


    }



My Source code is:

<asp:ListView ID="ListView1" runat="server" DataKeyNames="itemname" 

                DataSourceID="SqlDataSource1" 

                >
                   
                   
                   <EmptyDataTemplate>
                       No data was returned.
                   </EmptyDataTemplate>
                   
                   <ItemSeparatorTemplate>
                       <br />
                   </ItemSeparatorTemplate>
                   <ItemTemplate>
                       <li style="background-color: #DCDCDC; color: #000000;">Subitem Name:
                           <asp:Label ID="subitem_nameLabel" runat="server" 

                               Text='<%# Eval("subitem_name") %>' />
                           <br />
                           Item Description:
                           <asp:Label ID="item_descriptLabel" runat="server" 

                               Text='<%# Eval("item_descript") %>' />
                           <br />
                           Item Rate:
                           <asp:Label ID="item_rateLabel" runat="server" Text='<%# Eval("item_rate") %>' />
                           <br />
                           <asp:Button ID="btn_add" runat="server" Text="Add" CommandName="Select" OnClick="ListView1_SelectedIndexChanged" />
                       </li>
                   </ItemTemplate>
                   <LayoutTemplate>
                       <ul ID="itemPlaceholderContainer"  runat="server" 

                           style="font-family: Verdana, Arial, Helvetica, sans-serif;">
                           <li  runat="server" id="itemPlaceholder" />
                           
                           <br />
                           </li>
                       </ul>
                       <div style="text-align: center;background-color: #CCCCCC;font-family: Verdana, Arial, Helvetica, sans-serif;color: #000000;">
                       </div>
                   </LayoutTemplate>
                   
            </asp:ListView>



i have changed my code:

protected void ListView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        cnn.ConnectionString = ConfigurationManager.ConnectionStrings["jin"].ConnectionString;
        Control c = sender as Control;
        Label lbl =((Label)c.Parent.FindControl("subitem_nameLabel"));
        Label lbl2=((Label)c.Parent.FindControl("item_descriptLabel"));
        Label lbl3 = ((Label)c.Parent.FindControl("item_rateLabel"));
        Session["subitem_name"] = lbl.Text;
        Session["item_descript"] = lbl2.Text;
        decimal item_rate = Convert.ToDecimal(lbl3.Text);
        Session["item_rate"] = item_rate;

        try
        {
            cnn.Open();
            SqlCommand cm = new SqlCommand("str_order", cnn);
            cm.CommandType = CommandType.StoredProcedure;
            cm.Parameters.AddWithValue("@subitem_name", Session["subitem_name"]);
            cm.Parameters.AddWithValue("@item_descript", Session["item_descript"]);
            cm.Parameters.AddWithValue("@item_rate", Session["item_rate"].ToString());
            cm.ExecuteNonQuery();
            Response.Write("<script>('Items Added')</script>");
            cnn.Close();
        }
        catch (Exception ex)
        {
            //Response.Write("<script>('There is an Error while adding these Items')</script>");
            Response.Write(ex.Message);

        }


    }


And i am still getting error:
Conversion failed when converting the nvarchar value ''asdd'' to data type int.

解决方案

Try this:

Label lbl3 = ((Label)c.Parent.FindControl("item_rateLabel"));
         Session["subitem_name"]= lbl.Text;
         Session["item_descript"] = lbl2.Text;
         decimal item_rate = Convert.ToDecimal(lbl3.text); 
         Session["item_rate"] = item_rate;


USE [JIN]
GO
/****** Object:  StoredProcedure [dbo].[str_order]    Script Date: 03/13/2013 22:17:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[str_order]
@subitem_name nvarchar(50),
@item_descript nvarchar(100),
@item_rate decimal(18,2)
as
begin
declare @entrydate date
set @entrydate=GETDATE()
declare @time time
set @time= CURRENT_TIMESTAMP
declare @order_id nvarchar(50)
set @order_id=@subitem_name+convert (nvarchar(50),DAY(getdate()))
insert into Jin_order(subitem_name,item_descript,item_rate,entrydate,time,order_id)values(@subitem_name,@item_descript,@item_rate,@entrydate,@time,@order_id)
end




Try above stored procedure in your SQL server.

then execute below statement.

exec str_order ''asdd'',''test'',10.2


The SQL data type NVARCHAR is the variable-length Unicode string which is mapped by ADO.NET directly to the .NET class System.String. But of course not to a numeric type. You can further try to interpret the string as int using int.TryParse or int.Parse (this one can throw exception if the string is not parsed as integer).

But this case should make you thinking about your database schema. It''s likely that you are trying to use strings representing data instead of data itself. This is really, really bad thing. If the respective columns contain strings representing integer values, you should review your database schema and use one of SQL integer types instead of string.

—SA


这篇关于错误:将nvarchar值转换为数据类型int时转换失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆