Creating Datagridview at runtime - c#

I am at the end of the rope...
I am taking a value from a dateTimePicker and I am executing a SQL query based on the value from the dateTimePicker. The result of the query should be displayed on a Datagridview after executing the query.
Here is the code I have made so far:
namespace App1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DateTime varDate;
varDate = dateTimePicker1.Value;
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=SUBASH-LAPTOP\COBRA;Initial Catalog=Test;Integrated Security=True");
SqlCommand Command = con.CreateCommand();
Command.CommandText = "Select * From orders where date_purchased <= #varDate ";
con.Open();
SqlDataReader reader = Command.ExecuteReader();
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
DataGridView d1 = new DataGridView();
this.Controls.Add(d1);
while (reader.Read())
{
d1.DataSource = ds.Tables[0];
}
}
}
I pretty inexperienced with c# so any answers would be most appreciated.
Please help.
Thanks,
Subash

use this code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=SUBASH-LAPTOP\COBRA;Initial Catalog=Test;Integrated Security=True");
SqlCommand Command = con.CreateCommand();
SqlDataAdapter dp = new SqlDataAdapter("Select * From orders where date_purchased <= #varDate", con);
dp.SelectCommand.Parameters.AddWithValue("#varDate", dateTimePicker1.Value);
DataSet ds = new DataSet();
dp.Fill(ds);
DataGridView d1 = new DataGridView();
d1.DataSource = ds;
d1.DataMember = ds.Tables[0].TableName;
this.Controls.Add(d1);
}

Check out the Link below:
How to: Bind Data to the Windows Forms DataGridView Control
the DataGridView object reads in data from a "binding source" you have to link that to a TableAdapter that contains your SQL SELECT statement.
You're about 1/2 the way there. Getting the connection string working correctly is half the battle. The other half is finding out where your data is in relation to the DatagridView.
good Luck!

You have to add the parameter to the SqlCommand for it to be used:
Command.Parameters.AddWithValue("#varDate", DateTimePicker1.Value);

as i saw your code, you are missing assignment of parmeter value,
Command.CommandText = "Select * From orders where date_purchased <= #varDate ";
after this line you have to provide parmeter value to command object.
Command.Parameters.AddWithValue("#varDate", DateTimePicker1.Value);

Related

I want to insert data into a table

I'm building a C# Windows Forms database application. Data should be written in a text field and saved in a table using a button. My problem is that the data is not saved in the table.
I have built a list that should show the records of the table. When you click on the insert button, the text is displayed in the list, but it is not saved in the table.
My code:
private void insert_Click(object sender, EventArgs e)
{
string con_string = Properties.Settings.Default.DB1_ConnectionString;
SqlConnection con = new SqlConnection(con_string);
con.Open();
SqlCommand cmd = new SqlCommand("insert into tab_Musik values (#Titel,#Inerpret,#Genre)", con);
cmd.Parameters.AddWithValue("#Titel", int.Parse(txt_Titel.Text));
cmd.Parameters.AddWithValue("#Inerpret", txt_Interpret.Text);
cmd.Parameters.AddWithValue("#Genre", double.Parse(kmb_Genre.Text));
cmd.ExecuteNonQuery();
con.Close();
}
private void show[enter image description here][1]_Click(object sender, EventArgs e)
{
string con_string = Properties.Settings.Default.DB1_ConnectionString;
SqlConnection con = new SqlConnection(con_string);
con.Open();
SqlCommand cmd = new SqlCommand("select * from tab_Musik", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource=dt;
}
For the problem you described about clicking the insert button, the data cannot be saved to the table, you can try the following code:
private void btnAdd_Click(object sender, EventArgs e)
{
string con_string = "database connection string";
SqlConnection sqlConnection = new SqlConnection(con_string);
string myinsert = "insert into tab_Musik values (#Titel,#Inerpret)";
SqlCommand mycom = new SqlCommand(myinsert, sqlConnection);
mycom.Parameters.AddWithValue("#Titel", textBox1.Text);
mycom.Parameters.AddWithValue("#Inerpret", textBox2.Text);
sqlConnection.Open();
mycom.ExecuteNonQuery();
mycom.Clone();
mycom.Dispose();}
Show results:

How to insert into an identity column in MS SQL

I have the following code:
SqlCommand writeCommand = new SqlCommand("INSERT INTO computers(id)VALUES()", conn.GetConnection());
writeCommand.ExecuteNonQuery();
The table computers contains an INT idientity(1,1) column named id.
When I run the code, I get a System.Data.SqlClient.SqlException: Incorrect syntax near ')'. I've tried to find a solution, but can't find one on the internet.
If the table has other columns as well, and you want to populate them with NULL or their DEFAULT values, then you can use DEFAULT VALUES:
INSERT INTO dbo.computers
DEFAULT VALUES;
If, however, your table only have the one column, then personally using an IDENTITY is the wrong choice; a table that just has an IDENTITY is clearly being misused. Instead, use a SEQUENCE:
CREATE SEQUENCE dbo.Computers START WITH 1 INCREMENT BY 1;
This scales far better, and doesn't suffer the likely race conditions you have. Then, when running an INSERT (or similar) you would use NEXT VALUE FOR dbo.Computers.
For an auto-incrementing identity column the database handles the id value unless I missed something in what you are attempting to do.
public void DemoInsert(string ComputerName, ref int newIdentifier)
{
using (var conn = new SqlConnection { ConnectionString = ConnectionString })
{
using (var cmd = new SqlCommand { Connection = conn })
{
cmd.CommandText = "INSERT INTO computers (ComputerName) " +
"VALUES (#ComputerName); " +
"SELECT CAST(scope_identity() AS int);";
cmd.Parameters.AddWithValue("#ComputerName", ComputerName);
cn.Open();
newIdentifier = (int)cmd.ExecuteScalar();
}
}
}
I have similar code like your app, think about it simple crud app
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con;
SqlDataAdapter da;
SqlCommand cmd;
DataSet ds;
void fillGrid()
{
con = new SqlConnection("Data Source=.;Initial Catalog=schoolDb;Integrated Security=True");
da = new SqlDataAdapter("Select * from ogrenciler",con);
ds = new DataSet();
con.Open();
da.Fill(ds, "students");
dataGridView1.DataSource = ds.Tables["students"];
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
fillGrid();
}
private void Addbtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText="insert into students(StudentId,StudentName,StudentSurname,City) values("+StudentId.Text+",'"+StudentName.Text+"','"+StudentSurname.Text+"','"+City.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
private void Updatebtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "update Students set ogrenci_ad='"+StudentName.Text+"',StudentName='"+StudentSurname.Text+"',City='"+City.Text+"' where StudentId="+StudentId.Text+"";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
private void Deletebtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "delete from ogrenciler where ogrenci_no="+StudentId.Text+"";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
}
}

How To delete from both database and datagridview

So i've been looking around the google for the anwser to this found so many diffrenet anwsers but i do not quite understand them and dont really see the way to implement them even thoug i have tryed alot so my issue is basicly that my delete button only deletes from the datagridview and not the database itself i do have the gridview bound to my knowledge but this is the very first form app i make so im a bit puzzeld to what i am doing
private void buttonDel_Click(object sender, EventArgs e)
{///////////////////////////////////////////////////////issue is here
foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
dataGridView1.Rows.RemoveAt(item.Index);
}
//string del = "DELETE FROM Data WHERE RowID = #RowID";
}
using (SqlConnection Connection = new SqlConnection(Connectionstring))
{
string query = "insert into data(Navn, NummerPlade, KMKørt, dato)";
query += " values (#Navn, #NummerPlade, #KMKørt, #dato)";
Connection.Open();
SqlCommand cmd = new SqlCommand(query, Connection);
cmd.Parameters.AddWithValue("#Navn", textBox1.Text);
cmd.Parameters.AddWithValue("#NummerPlade", textBox8.Text);
cmd.Parameters.AddWithValue("#KMKørt", textBox6.Text);
cmd.Parameters.AddWithValue("#dato", textBox7.Text);
cmd.ExecuteNonQuery();
Connection.Close();
button4_Click(sender, e);
}
private void button4_Click(object sender, EventArgs e)
{
/// Connect / Update
using (SqlConnection Connection = new SqlConnection(Connectionstring))
{
Connection.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Data", Connection);
DataTable data = new DataTable();
sqlDa.Fill(data);
dataGridView1.DataSource = data;
}
buttonConn.Hide();
}

Unable to delete rows from DataGrid

Now this may be a "Noob" question. But I cant seem to do any commands that people seem to do with The DataGrid. What is the difference, and why can I only get DataGrid?
My problem is that I am trying to delete rows in the datagrid when they are pulled from a database. But, I cant figure out how because the SelectRows command does not work.
That is what i have so far. Is there anyway i can get DataGrid?
EDIT:
This is how I get information into the datagrid.
private void Button_Click(object sender, RoutedEventArgs e)
{
foreach (DataGridViewRow row in userDataGrid.SelectedRows)
{
if (!row.IsNewRow)
dataGridView1.Rows.Remove(row);
}
}
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=----; Database=----; User id=vsd; password=----";
conn.Open();
dt = new DataTable();
sda = new SqlDataAdapter("SELECT TeacherID, ClassName, ClassID FROM CLASS", conn);
sda.Fill(dt);
userDataGrid.ItemsSource = dt.DefaultView;
conn.Close();
Also, If there is a better way to do this, please let me know as well. I am very new to all of this.
Use the same instance of DataTable every time when you pull rows from db.
DataTable mDataTable = new DataTable(); //class field
public Constructor()
{
InitializeComponent();
userDataGrid.ItemsSource = mDataTable .mDataTable;
}
void PullData()
{
mDataTable.Clear();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
sda = new SqlDataAdapter("SELECT TeacherID, ClassName, ClassID FROM CLASS", conn);
sda.Fill(mDataTable );
}
}
It should solve your problem, but it's bad approach.
As Bizz adviced look at MVVM pattern & entity framework.
This is what I ended up doing for deleting the button. Most answers were trying to answer to a DataGridView. But, This is not WinForms or a DataGridView. This is WPF and its just DataGrid.
This is what I did to delete the row from the grid and the database.
private void delete_Click(object sender, RoutedEventArgs e)
{
DataGrid dg = this.aSSIGNMENTDataGrid;
var id1 = (DataRowView)dg.SelectedItem; //Get specific ID From DataGrid after click on Delete Button.
PK_ID = Convert.ToInt32(id1.Row["AssignmentID"].ToString());
SqlConnection conn = new SqlConnection(sqlstring);
conn.Open();
string sqlquery = "delete from ASSIGNMENT where AssignmentID='" + PK_ID + "' ";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
cmd.ExecuteNonQuery();
filldatagrid();
}
private void filldatagrid()
{
SqlConnection conn = new SqlConnection(sqlstring);
conn.Open();
string sqlquery = "select * from ASSIGNMENT";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
aSSIGNMENTDataGrid.ItemsSource = dt.DefaultView;
conn.Close();
}

A form is loaded but how to extract data from SQL to combobox?

Still learning C#
A comboBox is created and Tables called mainCat and subCat is created.
I have a code , but i am stuck to understand on how to get the data from mainCat to the comboBox , which is then used by another comboBox for the subCat to set a subcategory.
The Get Connection is underlined red. Why?
Here is my code -
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection Con = GetConnection())
{
SqlDataAdapter da = new SqlDataAdapter("Select Category.Category ,Category.Id from Category", Con);
SqlCommand cmd = new SqlCommand("SELECT * from MAINCAT");
DataTable dt = new DataTable();
da.Fill(dt);
mainCatU.DataSource = dt;
mainCatU.DisplayMember = "Category";
mainCatU.ValueMember = "Id";
mainCatU.Text = "<-Please select Category->";
myComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
}
}
So i then i tried another code.. but still doesnt work..
public partial class User : Form
{
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
private void User_Load(object sender, EventArgs e)
{
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Integrated Security=True";
con.Open();
MessageBox.Show("Database connected");
ds1 = new DataSet();
string sql = "SELECT * from MAINCAT";
da = new System.Data.SqlServerCe.SqlCeDataAdapter(sql, con);
da.Fill(ds1, "SCSID");
mainCatU.DataSource = ds1;
con.Close();
mainCatU.Text = "<-Please select Category->";
mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
mainCatU.Enabled = true;
}
}
then i just used the data bound item function through the combobox GUI..
this.mAINCATTableAdapter.Fill(this.masterDataSet.MAINCAT);
but , the box didn't show any value , except "System.Data.DataRowView" in the comboBox
==================================================================================
System.Data.SqlServerCe.SqlCeConnection con; //not used at the moment
System.Data.SqlServerCe.SqlCeDataAdapter da; //not used at the moment
DataSet ds1;
private void User_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
MessageBox.Show("Database connected");
SqlDataAdapter da = new SqlDataAdapter("SELECT * from MAINCAT", conn);
ds1 = new DataSet();
da.Fill(ds1, "MainCat");
mainCatU.DisplayMember = "maincat";
mainCatU.ValueMember = "maincat";
mainCatU.DataSource = ds1.Tables["MAINCAT"];
}
===============
and the combo box is still not showing anything from the database table
You need to create the function GetConnection():
public string ConnectionString { get; set;}
public SqlConnection GetConnection()
{
SqlConnection cn = new SqlConnection(ConnectionString);
return cn;
}
TBH, unless you want to do something in GetConnection, you might be better just creating it inline:
using (SqlConnection Con = new SqlConnection(ConnectionString))
{
EDIT:
Based on your revised question, I think the problem now may be here:
mainCatU.DisplayMember = "maincat";
mainCatU.ValueMember = "maincat";
mainCatU.DataSource = ds1.Tables["MAINCAT"];
My guess is that your table structure is not maincat.maincat. The display and value members should be set to the field name that you wish to display.
I am really sorry I am a vb developer but the concept is same to populate data into combo using sql is
Declare SQLConnection Declare SQLDataReader Declare SQLCommand
Try
If Con.State = ConnectionState.Closed Then
Con.Open()
cmd.Connection = Con
cmd.CommandText = "Select field1, field2 from table"
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBoxName.Items.Add(dr.GetString(0))
ComboBoxName.Items.Add(dr.GetString(1))
Loop
Con.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Hope it works for you.

Categories