Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
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:
C#
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.NET
<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:
C#
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.
Posted
Updated 13-Mar-13 9:02am
v4
Comments
Member 9581488 13-Mar-13 13:47pm    
Session["item_rate"] convert this to int if your @item_rate datatype is int.
Double check your datafield's datatype in database as well as in C# when you pass it to database.
Ankit_Sharma1987 13-Mar-13 13:50pm    
Thanks for reply, but sir i am using Stored proceedure:
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+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
so you can check this!!
Member 9581488 13-Mar-13 13:52pm    
what is the value of Session["item_rate"]?
Ankit_Sharma1987 13-Mar-13 13:57pm    
sir it is showing null, it is showing null, but when i was displaying, it on label then, it is,taking value....
Member 9581488 13-Mar-13 14:04pm    
Read the explanation in answer by SA.
If you cant troubleshoot the error, Try passing some static values to it.

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;
 
Share this answer
 
v2
Comments
Member 9581488 13-Mar-13 14:08pm    
decicaml item_rate = Convert.ToDecimal(lbl3.text);
should be
decimal item_rate = Convert.ToDecimal(lbl3.text);
Richard C Bishop 13-Mar-13 14:09pm    
Yes, I corrected it.
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
 
Share this answer
 
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
 
Share this answer
 
yes Problem with "[item_rate] [decimal](18, 2) NULL" in database

You can use Convert.ToDecimal(string) method. in your code

c
XML
nn.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", Convert.ToDecimal(Session["item_rate"].ToString()));
             cm.ExecuteNonQuery();
             Response.Write("<script>('Items Added')</script>");
             cnn.Close();
 
Share this answer
 
Comments
Ankit_Sharma1987 13-Mar-13 14:32pm    
thanks, sir, i have done , change in code, and here it is...
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"));
string subitem = Convert.ToString(lbl.Text);
Session["subitem_name"]= subitem;
string item_descript = Convert.ToString(lbl2.Text);
Session["item_descript"] = item_descript;
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.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);

}
Then also i am faceing the error:
Conversion failed when converting the nvarchar value 'Kalla Jheennga' to data type int.
[no name] 13-Mar-13 14:37pm    
First, do not use the Convert.AnyFunctions. Second, Converting a string to a string and sticking that in a string variable is dumb. Third, use AddWithValue and let the framework handle the conversion for you.
Ankit_Sharma1987 13-Mar-13 14:42pm    
Ok Sir now, is it correct?

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);

}
Richard C Bishop 13-Mar-13 15:05pm    
You will want to remove the .ToString() from this line:

cm.Parameters.AddWithValue("@item_rate", Session["item_rate"].ToString());
Ankit_Sharma1987 13-Mar-13 15:13pm    
Sir i have revoved..., now item_rate is in decimal, but it is showing same error...
Conversion failed when converting the nvarchar value 'asdd' to data type int.

sir this 'asdd' value, is coming from listview item template, "subitem_name"
this means error is coming from :
Session["subitem_name"] = lbl.Text;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900