Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
dear sir i haave the code for inserting data into data in asp.net c# 4.5


here 's the code:
--------------------------------
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

public partial class Register : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand command;
    SqlDataAdapter sda;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void txtsubmit_Click(object sender, EventArgs e)
    {
        string register_id = txtReg_id.Text;
        string name = txtName.Text;
        string contact = txtcontact.Text;

        con = new SqlConnection("Data Source=TUSHAR\\SQL;Initial Catalog=clrroom;Integrated Security=True");
        con.Open();
        try
        {
            string insertq = "insert into Register(Registration_id, Name,Contact,Role)"+ "values(@Registration_id,@Name,@Contact,@Role)";
            command = new SqlCommand(insertq,con);
            command.Parameters.Add("@Registration_id",SqlDbType.VarChar).Value=txtReg_id.Text.Trim();
            command.Parameters.Add("@Name",SqlDbType.VarChar).Value=txtName.Text.Trim();
            command.Parameters.Add("@contact",SqlDbType.VarChar).Value=txtcontact.Text.Trim();
            command.Parameters.Add("@Role",SqlDbType.VarChar).Value= drdpRole.SelectedItem;
            command.ExecuteNonQuery();

        }
        catch(Exception ex_)
        {
            Response.Write("Error occured"+ ex_.Message + "");
        }
        finally
        {
            con.Close();
        }

    }
}


What I have tried:

sir
i have ignored it after first execution of this page but shows this message ="Error occuredFailed to convert parameter value from a ListItem to a String."
Posted
Updated 29-Jul-16 0:42am
v2
Comments
Karthik_Mahalingam 29-Jul-16 6:41am    
are you getting any error?

C#
command.Parameters.Add("@Role",SqlDbType.VarChar).Value= drdpRole.SelectedItem;

The ListControl.SelectedItem Property (System.Web.UI.WebControls)[^] returns a ListItem, not a String. You should always check the documentation first for messages such as this.
 
Share this answer
 
Hello ,
Change
C#
command.Parameters.Add("@Role",SqlDbType.VarChar).Value= drdpRole.SelectedItem;

to
C#
command.Parameters.Add("@Role",SqlDbType.VarChar).Value= drdpRole.SelectedItem.Text;


Thanks
 
Share this answer
 

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