Click here to Skip to main content
15,606,999 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello guys, I added a DataGrid to my C# project and I have been unable to get it to populate the data after I click on the add button on the Windows Form. Anybody with any insight into what I might have overlooked?

What I have tried:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Point_of_sale
{
    public partial class manageCustomers : Form
    {
        public manageCustomers()
        {
            InitializeComponent();
        }
        SqlConnection Conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\GARNET6\Documents\inventorydb.mdf;Integrated Security=True;Connect Timeout=30");
        void populate()
        {
            try
            {
                Conn.Open();
                string Myquerry = "select * from CustomerTb1";
                SqlDataAdapter da = new SqlDataAdapter(Myquerry, Conn);
                SqlCommandBuilder builder = new SqlCommandBuilder(da);
                var ds = new DataSet();
                da.Fill(ds);
                CustomersGV.DataSource = ds.Tables[0];
                Conn.Close();


            }
            catch
            {

            }
        }
        private void label6_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void button1_Click(object sender, EventArgs e)
        {

            try
            {
                Conn.Open();
                SqlCommand cmd = new SqlCommand("insert into CustomerTb1 values('" + CustomerIdTb.Text + "', '" + CustomerNameTb.Text + "', '" + CustomerPhoneTb.Text + "', )", Conn);
                cmd.ExecuteNonQuery();
                MessageBox.Show("Customer sucessfully added");
                Conn.Close();
                populate();


            }

            catch
            {

            }
        }
        private void ManageCustomers_Load(object Sender, EventArgs e)
        {
            populate();
        }

        private void CustomersGV_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            CustomerIdTb.Text = CustomersGV.SelectedRows[0].Cells[0].Value.ToString();
            CustomerNameTb.Text = CustomersGV.SelectedRows[0].Cells[1].Value.ToString();
            CustomerPhoneTb.Text = CustomersGV.SelectedRows[0].Cells[2].Value.ToString();
        }

        private void manageCustomers_Load_1(object sender, EventArgs e)
        {
            populate();
        }
    }
}
Posted
Updated 21-Jan-22 4:26am
v2
Comments
Richard Deeming 21-Jan-22 11:49am    
In addition to the SQL Injection vulnerability explained in Solution 2, you should avoid storing SqlConnection objects in class-level fields. That will only lead to problems.

Create the connection when you need it, and wrap both the connection and command objects in using blocks to ensure they are always disposed-of properly.

You should also look to store your connection string in the application's configuration file, rather than hard-coding it. As it stands, nobody else will be able to run your application, because they will not have a C:\Users\GARNET6\ folder.

 
Share this answer
 
Comments
Sean Ewington 21-Jan-22 10:21am    
Thanks very much for your answer. While the link you've shared may be exactly the answer OP needs, we ask that answers be self-contained. The issue with links is that over time, they break. Using a link as a reference is fine, but we ask that the bulk of the answer be available here.
To add to what rick has said, dont; do it like that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?
 
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