I want to insert data into a table - c#

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:

Related

Dropdownlist Selected Item is not showing correct item

// fill from database
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string readnamesquery = "select cwFullTitle from tbCowWorkers";
cn.Open();
SqlCommand cmd = new SqlCommand(readnamesquery, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlUsers.DataSource = dt;
ddlUsers.DataValueField = "cwFullTitle";
ddlUsers.DataTextField = "cwFullTitle";
ddlUsers.DataBind();
cn.Close();
// insert selected value to database
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string registerQuery = "insert into Depot (dTdeliveryName) values (N'"+ddlUsers.SelectedValue.ToString()+"')";
SqlCommand cmd = new SqlCommand(registerQuery, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
I fill a Dropdownlist from SQL Server, then send selected item to another table in SQL Server; but it send first item of Dropdownlist as selected item.
Selected item didn't change and returns default value.
The reason is obvious, you are filling the dropdown list and then inserting the record, so it is bound to take the first item of the DropdownList.
I would suggest you separate the code of filling the dropdown list in another function and do the insertion only on selected_index change (ddl_SelectedIndexChanged) of DropDownList. In this ddl_SelectedIndexChanged function just check the selected value of the drop-down list and insert it to your target table (please remember to not invoke the call the function to load/Fill Dropdown List which you are currently doing in the shared code snippet).
SomeThing Like this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string readnamesquery = "select cwFullTitle from tbCowWorkers";
cn.Open();
SqlCommand cmd = new SqlCommand(readnamesquery, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlUsers.DataSource = dt;
ddlUsers.DataValueField = "cwFullTitle";
ddlUsers.DataTextField = "cwFullTitle";
ddlUsers.DataBind();
cn.Close();
}
}
protected void ddlUser_SelectedIndexChanged(object sender, EventArgs e)
{
// insert selected value to database
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string registerQuery = "insert into Depot (dTdeliveryName) values
(N'"+ddlUsers.SelectedValue.ToString()+"')";
SqlCommand cmd = new SqlCommand(registerQuery, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
Hope this Helps!
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Loading Dropdown by calling This.
LoadDdl();
}
}
//Load Dropdown From Database.
protected void LoadDdl(){
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string readnamesquery = "select cwFullTitle from tbCowWorkers";
cn.Open();
SqlCommand cmd = new SqlCommand(readnamesquery, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlUsers.DataSource = dt;
ddlUsers.DataValueField = "cwFullTitle";
ddlUsers.DataTextField = "cwFullTitle";
ddlUsers.DataBind();
cn.Close();
}
//Inserting Item to another table by selected index change.
protected void ddlUser_SelectedIndexChanged(object sender, EventArgs e)
{
//Checking If it's not the default value.
if(ddlUser.SelectedIndex != -1){
// insert selected value to database
SqlConnection cn = new SqlConnection(GlobalData.connectionstring);
string registerQuery = "insert into Depot (dTdeliveryName) values
(N'"+ddlUsers.SelectedValue.ToString()+"')";
SqlCommand cmd = new SqlCommand(registerQuery, cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}

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();
}

Use SQL queries virtual console to do any thing on a SQL Server database

How can I use a rich textbox and some pre-connected string to execute direct Transact-SQL queries and get results into a datagridview?
My GUI form is like this:
I want to use any SQL queries in this rich textbox and get result in data grid view
I using this code for query and fill data gridview
SqlConnection c = new SqlConnection(#"Data Source=.;Initial Catalog=db3;Integrated Security=True");
private void button1_Click(object sender, EventArgs e)
{
SqlDataAdapter a = new SqlDataAdapter("select * from phone", c);
DataTable t = new DataTable();
a.Fill(t);
dataGridView1.DataSource = t;
}
So how do I modify it to this?
SqlConnection c = new SqlConnection(#"Data Source=.;Initial Catalog=db3;Integrated Security=True");
private void button1_Click(object sender, EventArgs e)
{
SqlDataAdapter a = new SqlDataAdapter(Textbox1.Text, c);
DataTable t = new DataTable();
a.Fill(t);
dataGridView1.DataSource = t;
}
I also used Pravin Deshmukh code in another button and get error:
Update 3: used suggested code and got a reference error
private void button3_Click(object sender, EventArgs e)
{
string SqlString = textBox2.Text; // here you can have your user query from textbox
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Data Source=.;Initial Catalog=db3;Integrated Security=True"].ConnectionString.ToString());
conn.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(SqlString, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
conn.Close();
cmd.Dispose();
}
Error:
Try this
string SqlString= "your sql query";
SqlConnection conn = new SqlConnection(#"Data Source=.;Initial Catalog=db3;Integrated Security=True");
conn.Open();
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand(SqlString, conn);
cmd.CommandType = CommandType.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
conn.Close();
cmd.Dispose();
Set datagridview generate columns automatic
EDIT : or
string SqlString= textbox1.Text; // here you can have your user query from textbox

id getting inserted without selecting in c#.net

private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
con.Open();
OleDbDataReader DR = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(DR);
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "ID";
combo_status.Text = "Select Project Name";
}
private void btnSave_Click_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (#name)", con);
cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
In the first class i have a combobox and i am fetching its value from database and i have shown "Select Project Name" on page load in combobox.I want to insert its value only when user selects option from dropdown and insert nothing if user did not choose any option.
Now the problem is that the first name in the dropdown gets inserted on button click.without choosing any option.I want that if user did not choose any name value from dropdown nothing should get inserted.
can anyone help me..?
Assuming that datatype of ID column is int:
private void Form1_Load(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand cmd = new OleDbCommand("select project_name, ID from tb_project", con);
con.Open();
OleDbDataReader DR = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(DR);
//begin adding line
DataRow row = table.NewRow();
row["project_name"] = "Select Project Name";
row["ID"] = 0;
table.Rows.InsertAt(row, 0);
//end adding line
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "ID";
combo_status.Text = "Select Project Name";
}
private void btnSave_Click_Click(object sender, EventArgs e)
{
if(combo_status.SelectedValue == 0)
{
return; //do nothing if user didn't select anything in combobox, you can change this line of code with whatever process you want
}
OleDbConnection con = new OleDbConnection(constr);
con.Open();
OleDbCommand cmd = new OleDbCommand("Insert Into tb1(name) Values (#name)", con);
cmd.Parameters.AddWithValue("name", combo_status.SelectedValue);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Inserted sucessfully");
}
Hope this will help you

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