LP1
LP1

Reputation: 114

Insert data from radio button into database

Building a form application in C# for selling phones as a project. I have two radio buttons which the user checks based on what type of payment method they want cash or card.

How do I insert that data into the database based on what the user selects?

enter image description here

Upvotes: 0

Views: 226

Answers (3)

Rajesh Sawant
Rajesh Sawant

Reputation: 93

Luka,

Try it below. Add HTML Markup like:

<asp:CheckBox ID="chkCash" runat="server" />

.cs file add below code.

string Cash = chkCash.Checked ? "Y" : "N";

And send or add value like.

SqlCommand cmd = new SqlCommand("INSERT INTO Employees(Cash) VALUES(@Cash)"))
    {           
        cmd.Parameters.AddWithValue("@Cash", Cash);
    }

Upvotes: 0

LP1
LP1

Reputation: 114

I found the answer to my own question if someone needs it

try
{
    var connection = getConnection();
    connection.Open();

    if (CashRadio.Checked == true)
    {      
        var command = new SqlCommand
        {
            Connection = connection,
            CommandText ="INSERT INTO type_payment(cash,card) values(1,0)"
        };          
        command.Parameters.Clear();

        int result = command.ExecuteNonQuery();
        if (result > 0)
        {
            MessageBox.Show("Succsefully picked type");
        }
        else
        {
            MessageBox.Show("error");
        }
    }
    else if (CardRadio.Checked == true)
    {
        var command = new SqlCommand
        {
            Connection = connection,
            CommandText = "INSERT INTO type_payment(cash,card) values(0,1)"
        };
        command.Parameters.Clear();

        int result = command.ExecuteNonQuery();
        if (result > 0)
        {
            MessageBox.Show("Succesfully picked type");
        }
        else
        {
            MessageBox.Show("Error");
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

Upvotes: 0

lakshna S
lakshna S

Reputation: 273

You can try this,

protected void Button1_Click(object sender, EventArgs e)
    {
        string cs = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
        SqlConnection cn = new SqlConnection(cs);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = cn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into sample values(@payment)";
        cmd.Parameters.Clear();
        cmd.Parameters.AddWithValue("@payment", payment.SelectedValue);
        if (cn.State == ConnectionState.Closed)
            cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();
        lblmsg.Text = "Data entered successfully!!!";
    }

Upvotes: 1

Related Questions