Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i have textboxes where i can add data entered from there into my gridview.

when adding the data into the gridview,
Error occurs like
C#
Input string was not in a correct format.
Line 109:                        drCurrentRow = dtCurrentTable.NewRow();
Line 110:                        drCurrentRow["POID"] = Convert.ToInt64(POID.Text);
Line 111:                        drCurrentRow["ProductID"] = Int32.Parse(ID);
Line 112:                        drCurrentRow["Name"] = Name.Text;
Line 113:                        drCurrentRow["Quantity"] = Convert.ToInt32(Quantity.Text);



The productID doesn't have any textbox or label in my program.

I just get it by my products Dropdownlist Name.selectedvalue

Here is my code ASP

ASP.NET
<%@ Page Title="" Language="C#" MasterPageFile="~/Admin/Site.Master" AutoEventWireup="true" CodeBehind="PODetails.aspx.cs" Inherits="MyOwnMeatshop.Purchasing.Purchases.PODetails" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <style type="text/css">
        .style2
        {
            width: 172px;
        }
        .style3
        {
            width: 63px;
        }
    </style>



</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">


<br />
<br />
<br />
<form id="Form1" runat="server" class="form-horizontal">
         <div class="container">
            <div class="navbar-collapse collapse" id="navbar-main" style="height: 1px;">
                <ul class="nav navbar-nav">


                     <li>
                        <a id="a3" href="/Purchasing/Default.aspx" style="color: Gray" >Home</a>
                        
                    </li>
   
                    <li>
                        <a id="a45" href="/Purchasing/About.aspx" style="color: Gray" >About </a>
                        
                    </li>
                  

                    <li>
                        <a id="A10" href="/Purchasing/Inventory/Default.aspx" style="color: Gray">Inventory </a>
                        
                    </li>

                   

                     <li>
                        <a class="dropdown-toggle" data-toggle="dropdown" id="purch"  style="color: Gray">Purchases <span class="caret"></span> </a>
                        <ul class="dropdown-menu" style="background-color:Gray">
                            <li><a id="A1" href="~/Purchasing/Purchases/Default.aspx"  runat="server">View All Purchases</a></li>
                            <li><a id="A2" href="~/Purchasing/Purchases/Add.aspx"  runat="server">Add A Purchase</a></li>
                         </ul>
                        
                    </li>

                    <li>
                        <a class="dropdown-toggle" data-toggle="dropdown" id="supplier" style="color: Gray"> Suppliers <span class="caret"></span> </a>
                         <ul class="dropdown-menu" style="background-color:Gray">
                            <li><a id="suppdef" href="~/Purchasing/Supplier/Default.aspx"  runat="server">View All Suppliers</a></li>
                            <li class="divider" style="color:White"></li>
                            <li><a id="supp" href="~/Purchasing/Supplier/Add.aspx"  runat="server">Add A Supplier</a></li>
                        </ul>
                    </li>
                     <li>
                        <a class="dropdown-toggle" data-toggle="dropdown" id="A5" style="color: Gray">Reports </a>
                        <ul class="dropdown-menu" style="background-color:Gray">
                            <li><a id="p" href="~/Purchasing/Purchases/PrintList.aspx"  runat="server">Purchases List</a></li>
                             <li><a id="A6" href="~/Purchasing/Supplier/PrintList.aspx"  runat="server">Supplier List</a></li>
                        </ul>
                    </li>

                 </ul>
             </div>
          </div>
 <div class="container">
       
        <div class="col-lg-3">
            <h3>Sidebar</h3>
            <li>
              <a id="A4"  runat="server" href="~/Purchasing/Purchases/Default.aspx" style="color: Gray"> View All Purchases</a>
            </li>
    </div>


        <table >  
     
    <tr>  
         <td>#</td>  
       
        <td class="style2">  
            Product Name  
        </td> 
        
        <td>  
            Quantity  
        </td>  
         
    </tr>  
    <tr>  
     
      <td>
                    <asp:Label ID="POID" runat="server" BorderColor="Black" Font-Size="Larger" />
               </td>

     <td class="style2">   
        
        <asp:SqlDataSource ID="Products" runat="server" 
            ConnectionString="<%$ ConnectionStrings:MyOwnMeatshopConnectionString %>" 
            SelectCommand="SELECT [Name] FROM [Products]"  ></asp:SqlDataSource>
        <asp:DropDownList ID="Name" runat="server"  DataSourceID="Products" 
            DataTextField="Name" DataValueField="Name" Width="83px" ></asp:DropDownList>
     </td> 
         
        
      </td>  
     
      <td>  
      <asp:TextBox ID="Quantity" runat="server"></asp:TextBox>  
      </td>  
       
    </tr>  
    <tr>  
    <td class="style3"></td>  
    <td class="style2"></td>   
    <td>   
     
    </td>  
    <td>   
        <asp:Button ID="AddProduct" runat="server" Text="Add Product"   
            BackColor="#999966" onclick="AddProduct_Click" /></td>  
    </tr>  
   </table>
   <br />
   <br />
     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
             Width="333px" AllowPaging="True" 
            DataKeyNames="POID">
         <Columns>
           
             <asp:BoundField DataField="POID" HeaderText="POID" 
                 SortExpression="POID" InsertVisible="False" ReadOnly="True" />
             <asp:BoundField DataField="ProductID" HeaderText="ProductID" 
                 SortExpression="ProductID" />
             <asp:BoundField DataField="Name" HeaderText="Name" 
                 SortExpression="Name" />
             <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />
             <asp:BoundField DataField="Quantity" HeaderText="Quantity" 
                 SortExpression="Quantity" />
             
         </Columns>
     </asp:GridView>

        <asp:Button ID="btnsubmitProducts" runat="server" style="color:White"   
            Text="Save Products" BackColor="#999966" 
            onclick="btnsubmitProducts_Click" /> 

    </div>
    </form>

</asp:Content>


HERE is The Code behind

C#
public partial class PODetails : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(Helper.GetCon());
            
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!IsPostBack)
            {
                AddProducts();
                GetPO();
            }
        }


        void GetPO()
        {
            int GetPOID;
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "SELECT POID FROM PO";
            cmd.Parameters.AddWithValue("@UserID", Session["userid"].ToString());
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                POID.Text = dr["POID"].ToString();

            }
            con.Close();
        }

        int GetProductID(int ID) // get price of the selected product
        {
            int ProductID = 0;
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "SELECT ProductID FROM Products " +
                "WHERE Name=@PName";
            cmd.Parameters.AddWithValue("@Name", Name.SelectedValue);
            ProductID = (int)cmd.ExecuteScalar(); // typecasting

            con.Close();
            return ProductID;
        }


        void AddProducts()
        {
            GetPO();
            int ProductID;
            int GetSupplierID;
            ////con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            //creating DataTable  
            DataTable dt = new DataTable();
            DataRow dr;
            dt.TableName = "PODetails";
            //creating columns for DataTable  
            dt.Columns.Add(new DataColumn("POID", typeof(int)));
            dt.Columns.Add(new DataColumn("ProductID", typeof(int)));
            dt.Columns.Add(new DataColumn("Name", typeof(string)));
            dt.Columns.Add(new DataColumn("Price", typeof(decimal)));
            dt.Columns.Add(new DataColumn("Quantity", typeof(int)));
            dt.Columns.Add(new DataColumn("Amount", typeof(int)));
            
            dr = dt.NewRow();
            dt.Rows.Add(dr);

            ViewState["PODetails"] = dt;
            GridView1.DataSource = dt;
            GridView1.DataBind();  
        }

       

        void AddNewRecordRowToGrid()
        {
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            if (ViewState["PODetails"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["PODetails"];
                DataRow drCurrentRow = null;

                if (dtCurrentTable.Rows.Count > 0)
                {

                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {
                        int ProductID;
                        //Creating new row and assigning values  
                        drCurrentRow = dtCurrentTable.NewRow();
                        drCurrentRow["POID"] = Convert.ToInt64(POID.Text);
                        drCurrentRow["ProductID"] = Int32.Parse(ID);
                        drCurrentRow["Name"] = Name.Text;
                        drCurrentRow["Quantity"] = Convert.ToInt32(Quantity.Text);
                        //drCurrentRow["Price"] = Convert.ToDecimal(Price.Text);

                    }
                    //Removing initial blank row  
                    if (dtCurrentTable.Rows[0][0].ToString() == "")
                    {
                        dtCurrentTable.Rows[0].Delete();
                        dtCurrentTable.AcceptChanges();

                    }

                    //Added New Record to the DataTable  
                    dtCurrentTable.Rows.Add(drCurrentRow);
                    //storing DataTable to ViewState  
                    ViewState["PODetails"] = dtCurrentTable;
                    //binding Gridview with New Row  
                    GridView1.DataSource = dtCurrentTable;
                    GridView1.DataBind();
                }
            }
        }

        void BulkInsertToDataBase()
        {
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            DataTable dtPODetails = (DataTable)ViewState["PODetails"];
            //creating object of SqlBulkCopy  
            SqlBulkCopy objbulk = new SqlBulkCopy(con);
            //assigning Destination table name  
            objbulk.DestinationTableName = "PODetails";
            //Mapping Table column  
            objbulk.ColumnMappings.Add("Name", "Name");
            objbulk.ColumnMappings.Add("Quantity", "Quantity");
            //objbulk.ColumnMappings.Add("Price", "Price");
            //inserting bulk Records into DataBase   
            objbulk.WriteToServer(dtPODetails);
        }


        int GetSupplierID(int ID) // get price of the selected product
        {
            int GetSupplierID = 0;
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "SELECT SupplierID FROM Suppliers " +
                "WHERE SupplierID=@SupplierID";
            cmd.Parameters.AddWithValue("@SupplierID", ID);
            GetSupplierID = (int)cmd.ExecuteScalar(); // typecasting

            con.Close();
            return GetSupplierID;
        }

        
        protected void AddProduct_Click(object sender, EventArgs e)
        {
            GetPO();
            int GetSupplierID;

            int ProductID = 0;
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "SELECT ProductID FROM Products " +
                "WHERE Name=@Name";
            cmd.Parameters.AddWithValue("@Name", Name.SelectedValue);
            ProductID = (int)cmd.ExecuteScalar(); // typecasting

            con.Close();
            
            //con.Close();
            AddNewRecordRowToGrid();
            
        }

        protected void btnsubmitProducts_Click(object sender, EventArgs e)
        {
            BulkInsertToDataBase();
        }
Posted
Comments
Pauline Gail Chan 3-Feb-16 8:57am    
Help guys thanks!!

This is the classic case of: use your debugger...
1. Let it stop on the line with the error (probably Int32.Pares(ID))
2. Examine the code and the data (sometimes the code looks OK, but the data changes everything)

(Hint. ID may be empty or non-numeric.)
 
Share this answer
 
Comments
Pauline Gail Chan 3-Feb-16 19:14pm    
okay im gonna try. But if the ProductID is Null this error will continuously show?
Kornfeld Eliyahu Peter 4-Feb-16 1:46am    
Int is not nullable so NULL can not be converted to int...
Just change the follwing code
C#
drCurrentRow["ProductID"] = Int32.Parse(ID);

to like this
C#
drCurrentRow["ProductID"] = Int32.Parse(Name.SelectedValue);

Better option is check the combo value before adding to the data table as mentioned below
C#
int ID = 0
if(int.TryParse(Name.SelectedValue, out ID)
{
  //put your all logic here
  drCurrentRow["ProductID"] =  ID;
}
else
 throw error or validation message
 
Share this answer
 
I doubt for row 110, the code Convert.ToInt64() does not return int it returns long.
Line 110:                        drCurrentRow["POID"] = Convert.ToInt64(POID.Text);


Also please make sure the assignments using Immediate window ( CTRL + ALt + I), and use break points to find out the actual line of error.

Thanks
 
Share this answer
 

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

  Print Answers RSS


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