Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to insert new values in sql db..by selecting different tables from combo box

Tags:

c#

sql-server

well I have made this program to insert new values in SQL db,by choosing between different tables from combo box.I need to change the sql query by which I can use insert command individually for each table in combo box...the area where i need help is in bold ...

namespace combo
{
    public partial class Form1 : Form
    {
        List lstNewRows = new List();

        public Form1()
        {
            InitializeComponent();
        }
        private void PopulateComboBox()
        {
            try
            {

                List _items = new List();

                _items.Add("select * from lol");
                _items.Add("select * from datejoin");
                comboBox1.DataSource = _items;

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            PopulateComboBox();
        }

        private void PopulateGridView(string connString, string sqlQuery)
        {

            String strconnetcion = connString;

            SqlConnection con = new SqlConnection(strconnetcion);



            try
            {

                con.Open();

                SqlCommand sqlCmd = new SqlCommand();

                sqlCmd.Connection = con;
                sqlCmd.CommandType = CommandType.Text;
                sqlCmd.CommandText = sqlQuery;

                SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);

                DataTable dtRecord = new DataTable();
                sqlDataAdap.Fill(dtRecord);

                dataGridView1.DataSource = dtRecord;
                dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedValue != null)
            {
                PopulateGridView(textBox1.Text, comboBox1.SelectedValue.ToString());
            }
        }

        private void InsertInfo()
        {

            string connectionString = null;
            SqlConnection connection;
            SqlDataAdapter adapter = new SqlDataAdapter();
            string value1 = "";
            string value2 = "";
            connectionString = @"Data Source=HP\SQLEXPRESS;database=MK;Integrated Security=true";
            connection = new SqlConnection(connectionString);
            foreach (int rowIndex in lstNewRows)
            {
                if (dataGridView1.Rows[rowIndex].Cells[0].Value != null && dataGridView1.Rows[rowIndex].Cells[1].Value != null)
                {

                    value1 = dataGridView1.Rows[rowIndex].Cells[0].Value.ToString();
                    value2 = dataGridView1.Rows[rowIndex].Cells[1].Value.ToString();
                    ***string sql = "insert into lol (name,marks) values('" + value1 + "','" + value2 + "')";***
                    try
                    {
                        connection.Open();
                        adapter.InsertCommand = new SqlCommand(sql, connection);
                        adapter.InsertCommand.ExecuteNonQuery();
                        MessageBox.Show("Row inserted !! ");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }

                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {


            InsertInfo();

        }

        private void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
            lstNewRows.Add(e.Row.Index);
        }
    }
}
like image 935
Mayuri Koul Avatar asked Dec 08 '25 09:12

Mayuri Koul


1 Answers

After going through the source, I understand what you are trying to accomplish. I will give my answer your problem first, but please read the recommendations after the answer because proceeding in the way you are onto now this application may end up as a big headache to whoever is going to maintain it.

Answer:

Change your items to be as follows:
List _items = new List();
_items.Add("lol"); // removing select * from 
_items.Add("datejoin"); // removing select * from 
comboBox1.DataSource = _items;

Now in your PopulateGridView function you can change the sqlQuery to

private void PopulateGridView(string connString, string sqlQuery) {
    sqlQuery = "select * from "+sqlQuery;

then in your InsertInfo function you can do the following (at the location where you are defining the string sql variable):

string sql = string.Empty;
switch(comboBox1.SelectedValue) {
    case "lol":
        sql = "insert into lol (name,marks) values('" + value1 + "','" + value2 + "')";
        break;
    case "datejoin":
        sql = "insert into datejoin (..."; // fill in the column and values as needed
        break;
}

Recommendations:

  1. Please change your vanilla string queries to stored procedures or look into LINQ
  2. Do not use select *, always try to mention the column names in a select query
  3. Provide a more user friendly name in the combobox than the table name, it is not always safe to make the table names so obvious to the end user
  4. Try using a separate data access layer and move the database specific codes into that layer

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!