I'm new in C# and I don't know how to view data of MySQL in a form. I have already fixed to create a delete button and an add button but now I also want to view that data in the form. I looked up all kinds of things to get it working, but I just can't get it done. Does anyone know what I need to do to get it work?
Here is how I want to view the data: https://i.stack.imgur.com/4Yixa.png
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Test
{
public partial class Apparatenlijst : Form
{
string MyConnectionString = "Server=localhost;Database=apparatuur;Uid=root;Pwd=;";
public Apparatenlijst()
{
InitializeComponent();
}
private void Apparatenlijst_Load(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string apparaatt = toevoegg.Text;
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO lijst(apparaatnaam)VALUES(#apparaatnaam)";
cmd.Parameters.AddWithValue("#apparaatnaam", apparaatt);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
MessageBox.Show("Apparaat succesvol toegevoegd");
}
}
}
private void button2_Click(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void verwijder_Click(object sender, EventArgs e)
{
string apparaata = verwijderr.Text;
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "DELETE FROM lijst WHERE apparaatnaam=#apparaatnaam";
cmd.Parameters.AddWithValue("#apparaatnaam", apparaata);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
MessageBox.Show("Apparaat succesvol verwijderd");
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void lvStudents_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Are you using ListView to display the data?
You can call method MySqlDataAdapter.Fill() to get the datatable from data source. For this, you need to install Nuget package MySql.Data.
Then traverse the datatable and add new ListViewItem object to the ListView.
string constr = #"connection string";
using (MySqlConnection conn = new MySqlConnection(constr))
{
MySqlDataAdapter sda = new MySqlDataAdapter("Select * From lijst", conn);
DataSet ds = new DataSet();
sda.Fill(ds);
listView1.BeginUpdate();
foreach (DataRow row in ds.Tables[0].Rows)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = row["Field1"].ToString();
lvi.SubItems.Add(row["Field2"].ToString());
lvi.SubItems.Add(row["Field3"].ToString());
listView1.Items.Add(lvi);
}
listView1.EndUpdate();
}
Related
First, I'm really sorry about my English pronounciation. I have a datagridview, and i connect it to sql server which has been dip into my project in visual studio. However, when i save info in datagridview, it works but in database it is not saved in my database in sql server. Can you help me, please
And this is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Lab3_Bai09
{
public partial class Form1 : Form
{
SqlConnection cnn = null;
string connetionString;
public Form1()
{
InitializeComponent();
connetionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\QLSV.mdf;Integrated Security=True";
cnn = new SqlConnection(connetionString);
cnn.Open();
cnn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
txtB2.Text = txtB1.Text;
}
private void button2_Click(object sender, EventArgs e)
{
txtB1.Text = txtB2.Text;
}
private void Save_Click(object sender, EventArgs e)
{
cnn.Open();
SqlCommand sqlCommand;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = "";
string sex = "";
if(checkBox1.Checked == true)
{
sex = "Nam";
}
else
{
sex = "Nu";
}
string[] subjectList = txtB1.Text.Split('\n');
int countSubject = subjectList.Length;
sql = $"insert into SINHVIEN(MSSV, HOTEN, CHUYENNGANH, GIOITINH, SOMON) values ('{textBox1.Text}', '{textBox2.Text}', '{comboBox1.Text}', '{sex}', '{countSubject}')";
sqlCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Đã thêm mới dữ liệu thành công!");
this.sINHVIENTableAdapter1.Fill(this.qLSVDataSet1.SINHVIEN);
textBox1.Clear();
textBox2.Clear();
checkBox1.Checked = false;
checkBox2.Checked = false;
txtB1.Clear();
txtB2.Clear();
cnn.Close();
}
private void Delete_Click(object sender, EventArgs e)
{
cnn.Open();
DialogResult result = MessageBox.Show("Bạn có muốn xóa dòng đã chọn?", "Delete", MessageBoxButtons.YesNoCancel);
if (result == DialogResult.Yes)
{
SqlCommand sqlCommand;
SqlDataAdapter adapter = new SqlDataAdapter();
string sql = "";
int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
string c = selectedRow.Cells[0].Value.ToString();
sql = $"delete from SINHVIEN where MSSV = {c}";
sqlCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Xóa dữ liệu thành công");
this.sINHVIENTableAdapter1.Fill(this.qLSVDataSet1.SINHVIEN);
}
cnn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'qLSVDataSet1.SINHVIEN' table. You can move, or remove it, as needed.
this.sINHVIENTableAdapter1.Fill(this.qLSVDataSet1.SINHVIEN);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
DialogResult result = MessageBox.Show("Bạn có muốn thoát?", "Exit", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
Application.Exit();
}
else
{
e.Cancel = true;
}
}
else
{
e.Cancel = true;
}
}
}
}
It looks like you are just pulling values from text boxes and a combo box. There is a line for this.sINHVIENTableAdapter1.Fill(this.qLSVDataSet1.SINHVIEN); but where are those declared? I don't see you calling anything that writes the data back to the database from that adapter or dataset. After you declare the sqlCommand, you write a new instance of an sql command into the adapter, do you mean to do that?
sqlCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand.ExecuteNonQuery();
I will say that you are leaving yourself wide open for SQL injection. The SQL INSERT should be handled more like this:
sql = $"insert into SINHVIEN(MSSV, HOTEN, CHUYENNGANH, GIOITINH, SOMON) values (#mssv, #hoten, #chuy, #sex, #countsub)";
sqlCommand = new SqlCommand(sql, cnn);
sqlCommand.Parameters.AddWithValue("#mssv", textBox1.Text);
sqlCommand.Parameters.AddWithValue("#hoten", comboBox1.Text);
sqlCommand.Parameters.AddWithValue("#chuy", textBox2.Text);
sqlCommand.Parameters.AddWithValue("#sex", sex);
sqlCommand.Parameters.AddWithValue("#countSub", countSubject);
adapter.InsertCommand = sqlCommand;
adapter.InsertCommand.ExecuteNonQuery();
See this post for how to bind a datagridview to a datatable: How to bind Dataset to DataGridView in windows application.
I have an sqladapter declared inside a private void and I cant refence it for the update void.
Can anyone advise where I should declare it so it is available in the whole script please?
SqlAdapter is called sqlDataAdap.
The sqladapter is declared in the GetList void and then needs to be called in here but cant be referenced.
private void UpdateRowToDatabase() {
if (LastDataRow!=null) {
if (LastDataRow.RowState==
DataRowState.Modified) {
sqlDataAdap.Update(LastDataRow);
}
}
}
Cheers for the help - it's hard being a newb again!
Dave
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System;
using System.Data.SqlClient; //For SQL Connection
namespace Reference_Table_Updater
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
}
void GetList()
{
String strConnection = "server=myserver';" +
"Database='Scratchpad';" +
"Integrated Security=SSPI";
SqlConnection con = new SqlConnection(strConnection);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from dbo.UPDATE_Test";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;
dataGridView1.Refresh();
//con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
GetList();
}
private DataRow LastDataRow = null;
private void UpdateRowToDatabase() {
if (LastDataRow!=null) {
if (LastDataRow.RowState==
DataRowState.Modified) {
sqlDataAdap.Update(LastDataRow);
}
}
}
private void regionBindingSource_PositionChanged(
object sender, EventArgs e)
{
BindingSource thisBindingSource =
(BindingSource)sender;
DataRow ThisDataRow=
((DataRowView)thisBindingSource.Current).Row;
if (ThisDataRow==LastDataRow) {
throw new ApplicationException("It seems the" +
" PositionChanged event was fired twice for" +
" the same row");
}
UpdateRowToDatabase();
LastDataRow = ThisDataRow;
}
private void MainForm_FormClosed(
object sender, FormClosedEventArgs e)
{
UpdateRowToDatabase();
}
}
}
I have listview that is getting data from sql database .. I want to search by text entered in textbox and show the result after clicking a button and hide the records that doesn't match
here's my approach
plz help
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Inventory_Manager_Pro
{
public partial class Modify : Form
{
public SqlConnection cn = new SqlConnection("Data Source=10.0.0.13;Initial Catalog=INVENTDB;Persist Security Info=True;User ID=sa;Password=farespila010A#;Encrypt=False");
public Modify()
{
InitializeComponent();
}
private void populate()
{
listView1.Items.Clear();
SqlCommand cm = new SqlCommand("SELECT * FROM lapdev", cn);
try
{
SqlDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
ListViewItem it = new ListViewItem(dr["fillingcode"].ToString());
it.SubItems.Add(dr["username"].ToString());
it.SubItems.Add(dr["branch"].ToString());
it.SubItems.Add(dr["department"].ToString());
it.SubItems.Add(dr["agency"].ToString());
it.SubItems.Add(dr["computername"].ToString());
it.SubItems.Add(dr["lapmodel"].ToString());
it.SubItems.Add(dr["lapserial"].ToString());
it.SubItems.Add(dr["assetnumber"].ToString());
it.SubItems.Add(dr["os"].ToString());
it.SubItems.Add(dr["winlicense"].ToString());
it.SubItems.Add(dr["office"].ToString());
it.SubItems.Add(dr["officelicense"].ToString());
it.SubItems.Add(dr["hddsize"].ToString());
it.SubItems.Add(dr["processor"].ToString());
it.SubItems.Add(dr["ram"].ToString());
it.SubItems.Add(dr["macadress"].ToString());
it.SubItems.Add(dr["ipadress"].ToString());
listView1.Items.Add(it);
}
dr.Close();
dr.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Modify_Shown(object sender, EventArgs e)
{
try
{
cn.Open();
populate();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
private void button1_Click(object sender, EventArgs e)
{
listView1.Items.Clear(); // clear list items before adding
listView1.Items.AddRange(Items.Where(i=>string.IsNullOrEmpty(textBox1.Text)||i.Name.StartsWith(textBox1.Text))
.Select(c => new ListViewItem(c.Name)).ToArray());
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
}
}
}
In your pupolate method do this:
private void populate()
{
listView1.Items.Clear();
SqlCommand cm;
if(textBox1.Text == "")
cm = new SqlCommand("SELECT * FROM lapdev", cn);
else
cm = new SqlCommand("SELECT * FROM lapdev WHERE YourField='" + textBox1.Text + "'", cn);
try
{
SqlDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
ListViewItem it = new ListViewItem(dr["fillingcode"].ToString());
it.SubItems.Add(dr["username"].ToString());
it.SubItems.Add(dr["branch"].ToString());
it.SubItems.Add(dr["department"].ToString());
it.SubItems.Add(dr["agency"].ToString());
it.SubItems.Add(dr["computername"].ToString());
it.SubItems.Add(dr["lapmodel"].ToString());
it.SubItems.Add(dr["lapserial"].ToString());
it.SubItems.Add(dr["assetnumber"].ToString());
it.SubItems.Add(dr["os"].ToString());
it.SubItems.Add(dr["winlicense"].ToString());
it.SubItems.Add(dr["office"].ToString());
it.SubItems.Add(dr["officelicense"].ToString());
it.SubItems.Add(dr["hddsize"].ToString());
it.SubItems.Add(dr["processor"].ToString());
it.SubItems.Add(dr["ram"].ToString());
it.SubItems.Add(dr["macadress"].ToString());
it.SubItems.Add(dr["ipadress"].ToString());
listView1.Items.Add(it);
}
dr.Close();
dr.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
and in your button click event:
private void button1_Click(object sender, EventArgs e)
{
//listView1.Items.Clear(); // clear list items before adding
populate();
//you type what you want in textbox then click button.
}
you dont even need to call clear on button click because populate method already takes care of that.
I made an application who updates a sqlce database.
The problem is, when I try to delete something it says "InvalidArgument=Value of '1' is not valid for 'index'."
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlServerCe;
namespace Database_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public SqlCeConnection conn = new SqlCeConnection(#"Data Source=C:\automail.sdf");
////////////////////////////////////Methodes////////////////////////////////////
private void Populate()
{
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM Emails ORDER BY principalID", conn);
listView1.Items.Clear();
try
{
SqlCeDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
ListViewItem it = new ListViewItem(dr["principalID"].ToString());
it.SubItems.Add(dr["query"].ToString());
it.SubItems.Add(dr["email"].ToString());
it.SubItems.Add(dr["subject"].ToString());
listView1.Items.Add(it);
}
dr.Close();
dr.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Application.ExitThread();
}
}
////////////////////////////////////Methodes////////////////////////////////////
// Insert button (for data insert)
private void button1_Click(object sender, EventArgs e)
{
if ( txtEmail.Text == "" || txtQuery.Text == "")
{
MessageBox.Show("Fill in all the information first!");
}
else
{
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Emails(principalID, email, query, subject) VALUES(#principalID, #email, #query, #subject)", conn);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#principalID", txtPrincipal.Text);
cmd.Parameters.AddWithValue("#email", txtEmail.Text);
cmd.Parameters.AddWithValue("#query", txtQuery.Text);
cmd.Parameters.AddWithValue("#subject", txtSubject.Text);
try
{
int affectedrows = cmd.ExecuteNonQuery();
if (affectedrows > 0)
{
Populate();
MessageBox.Show("Email added successfully!");
txtEmail.Clear();
txtPrincipal.Clear();
txtQuery.Clear();
txtSearch.Clear();
txtSubject.Clear();
}
else
{
MessageBox.Show("Failed to add email!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//if form shown fill the listview with the new information of the database
private void Form1_Shown(object sender, EventArgs e)
{
try
{
conn.Open();
Populate();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
Application.ExitThread();
}
}
//open form 2 and hide this
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
}
//if listview selected enable button, else disable
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
//enable delete button
button3.Enabled = true;
ListViewItem itm = listView1.SelectedItems[0];
string principalid = itm.SubItems[0].Text;
string query = itm.SubItems[1].Text;
string email = itm.SubItems[2].Text;
string subject = itm.SubItems[3].Text;
txtPrincipal.Text = principalid.ToString();
txtEmail.Text = email.ToString();
txtQuery.Text = query.ToString();
txtSubject.Text = subject.ToString();
}
else
{
button3.Enabled = false;
}
}
private void button3_Click(object sender, EventArgs e)
{
}
//delete record button
private void button3_Click_1(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count <= 0)
{
MessageBox.Show("Select a record!");
}
else
{
ListView.SelectedListViewItemCollection items = this.listView1.SelectedItems;
//for (int i = 0; i < listView1.SelectedItems.Count; i++)
foreach(ListViewItem item in items)
{
SqlCeCommand cm = new SqlCeCommand("DELETE * FROM Emails WHERE query ='" + listView1.SelectedItems[1].Text + "'", conn);
try
{
cm.ExecuteNonQuery();
Populate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
// if button clicked, transfer information out of the records selected to form2
private void button2_Click_1(object sender, EventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure you want to close this application?\nThis will terminate all systems which are active at the moment","Close", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
}
if (result == DialogResult.No)
{
e.Cancel = true;
}
}
private void button4_Click(object sender, EventArgs e)
{
//try
//{
// SqlCeCommand cm = new SqlCeCommand("SELECT * FROM Emails where principalID like " + txtSearch.Text, conn);
//}
//catch (Exception ex)
//
// MessageBox.Show(ex.Message);
//}
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
}
}
}
It throws the error at
SqlCeCommand cm = new SqlCeCommand("DELETE * FROM Emails WHERE query ='" + listView1.SelectedItems[1].Text + "'", conn);
Can someone help me please? I've already tried with parameters, but still no luck...
It worked fine before I imported an CSV file into my database with a tool, but the database structure is still the same, so it should be able to delete everything I select.
You can not use * with where condition in delete command ..so TRY like this....
SqlCeCommand cm = new SqlCeCommand("DELETE FROM Emails WHERE query ='" + listView1.SelectedItems[0].Text + "'", conn);
Ignoring the other issues in your code (security of your Sql, etc), I believe this is the specific problem you're asking about.
You're using this:
listView1.SelectedItems[1].Text
... but arrays and lists in C# are zero-absed, and so the first selected item is actually this:
listView1.SelectedItems[0].Text
It's also worth noting that, since you call this in a loop, you will try to delete this single item once for every item in the list. I suspect the loop is redundant or, alternatively, your commented out loop (through each selected item) is what you really want, and in that case you mean this:
listView1.SelectedItems[i].Text
... which would use the text of each item in turn as you loop.
I have created a database using SQL Server Management Studio and am now trying to edit that database using Visual Studio Express 2012. I have connected the database to Visual Studio and can see my database but I have not been able to edit the database stored in Management Studio using Visual Studio. I have created a form and am trying to insert what is entered into textbox1 into a specific cell on my database after the user defines the column name and row (using the primary key in my DB) with textbox2 and textbox3. What code can I use to perform this action? So far I have had no luck. Thank you in advance for you help.
This is my current code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
using Microsoft.SqlServer.Server;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection myConnectionString = new SqlConnection("Data Source=Server Catalog=DataBase;Integrated Security=True");
SqlCommand command = new SqlCommand();
private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection dbConnection = new SqlConnection()) // the "using" construct will close and dispose of the connection
{
dbConnection.ConnectionString = ("Data Source=Server ;Initial Catalog=Database;Integrated Security=True");
dbConnection.Open();
maskedTextBox1.Clear();
dateTimePicker1.Value = DateTime.Now.AddDays(0);
comboBox1.SelectedIndex = -1;
String username = comboBox2.Text;
using (SqlCommand command = new SqlCommand("INSERT INTO [Table Name] (Column Name) VALUES ([Parm1])", dbConnection))
{
command.Parameters.AddWithValue("Parm1", username);
command.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
//Close the Window
this.Close();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void comboBox1_DataSourceChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
myConnectionString.Open();
MessageBox.Show("Sql is connected");
myConnectionString.Close();
}
}
}
The VALUES clause should specify a parameter and that parameter should be specified when adding the parameter value. Try substituting the following:
String sqlquery = "INSERT INTO [Man Power] ([Person_Performing_Phase_2]) VALUES ([Parm1])";
SqlCommand command = new SqlCommand(sqlquery, con);
command.Parameters.AddWithValue("Parm1", username);
EDIT
Your connection string is incorrectly formed. I believe the following format is appropriate for your current needs:
String myConnectionString = Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
I would use the following code for inserting data, which opens and closes the connection for each operation. Note the "command.ExecuteNonQuery" statement - its omission is why your insert failed to work - although I am unsure why opening the connection did not throw an error.
private void button3_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection dbConnection = new SqlConnection()) // the "using" construct will close and dispose of the connection
{
dbConnection.ConnectionString = myConnectionString;
dbConnection.Open();
maskedTextBox1.Clear();
dateTimePicker1.Value = DateTime.Now.AddDays(0);
comboBox1.SelectedIndex = -1;
String username = comboBox2.Text;
using (SqlCommand command = new SqlCommand("INSERT INTO [Man Power] ([Person_Performing_Phase_2]) VALUES ([Parm1])", dbConnection))
{
command.Parameters.AddWithValue("Parm1", username);
command.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
You should also remove all other _Click methods and replace the connection and command statement with the myConnectionString assignement.