c#.net winforms [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
i am new to c#.net i found the following code in the web and i modified it but its not working
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 InsertUpdateDeleteDataGridView
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\bj\documents\visual studio 2013\Projects\InsertUpdateDeleteDataGridView\InsertUpdateDeleteDataGridView\Information.mdf;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter adapt;
//ID variable used in Updating and Deleting Record
int id = 0;
public Form1()
{
InitializeComponent();
//invok fn
DisplayData();
}
private void btninsert_Click(object sender, EventArgs e)
{
if(txtbxname.Text!="" && txtbxcountry.Text!="")
{
cmd = new SqlCommand("INSERT INTO users(name,country) VALUES(#name,#country)",con);
con.Open();
cmd.Parameters.AddWithValue("#name", txtbxname.Text);
cmd.Parameters.AddWithValue("#country", txtbxcountry.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("record added succesfully","Success");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("please provide Details!","Error");
}
}
//displaying Data in DataGridView
private void DisplayData()
{
con.Open();
//creating obj of datatable method
DataTable dt= new DataTable();
dt = null;
adapt.Fill(dt);
dataGridView1.DataSource=dt;
con.Close();
}
//clearing datat
private void ClearData()
{
txtbxname.Text="";
txtbxcountry.Text="";
id=0;
}
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
id=Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txtbxname.Text=dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txtbxcountry.Text=dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
}
//update record
private void btnupdate_Click(object sender, EventArgs e)
{
if(txtbxname.Text!="" && txtbxcountry.Text!="")
{
cmd=new SqlCommand("UPDATE users SET name=#name,state=#state WHERE id=#id ",con);
con.Open();
cmd.Parameters.AddWithValue("#id",id);
cmd.Parameters.AddWithValue("#name",txtbxname.Text);
cmd.Parameters.AddWithValue("#country",txtbxcountry.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("record updated succesfully","success");
con.Close();
DisplayData();
ClearData();
}
else
{
MessageBox.Show("please select the record to update!","erorrr!!");
}
}
//deleterecord
private void btndelete_Click(object sender, EventArgs e)
{
if(txtbxname.Text!="" && txtbxcountry.Text!="")
{
cmd=new SqlCommand("DELETE students WHERE id=#id",con);
con.Open();
cmd.Parameters.AddWithValue("#id",id);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("record deleted successfully!");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("please select record to delete","error");
}
}
}
}
but when ever i try to run there is exception called in this line
adapt.filldata(dt);
private void DisplayData()
{
con.Open();
//creating obj of datatable method
DataTable dt= new DataTable();
dt=null;
adapt = new SqlDataAdapter("Select *from users ", con);
adapt.Fill(dt);
dataGridView1.DataSource=dt;
con.Close();
}
i again modified my creating object but the result is ame
i searched a lot but didnot got any answer so i am got stucked is there any one to help me

The adapt object has not been instantiated. You need to to create the object first.
this article gives a simple example of how to create the adapter and then call the fill method. you can not call methods on objects before creating them.
https://msdn.microsoft.com/en-us/library/bh8kx08z(v=vs.110).aspx

Related

How to save data when i add in datagridview into database sql server

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.

the process can not access the file 'bin\debug' because it is being used by another process

this is my code
i have tried every step i can find
i have moved con.close(); before and after it is still not working
please guide me to what to do
thank you
I am following this youtube video to make the crud operation https://www.youtube.com/watch?v=C7ukAjQtsxE
using System.Data;
using System.Data.SqlClient;
namespace crudingtime
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=DESKTOP-6381H14\\SQLEXPRESS;Initial Catalog=yarabthis;Integrated Security=True");
private void Form1_Load(object sender, EventArgs e)
{
GetEmpList();
}
private void imtired_Click(object sender, EventArgs e)
{
con.Open();
int id = int.Parse(idbox.Text);
string fname=fnametxt.Text, lname=lnametxt.Text;
SqlCommand c = new SqlCommand("exec ughh'"+id+"','"+fname+"','"+lname+"','",con);
con.Close();
MessageBox.Show("Successfully inserted");
}
void GetEmpList()
{
SqlCommand c = new SqlCommand("exec Listughh", con);
SqlDataAdapter sd=new SqlDataAdapter(c);
DataTable dt = new DataTable();
sd.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}```
don't try and persist the connection at the form class level - since then you can't control when you dispose of it.
So, try say like this, and always have a using code block (which will clean up all your connections for you).
And it not clear why you have a public form method here, so let's just leave that issue out of the picture for the time being.
and I assume that a hard coded connection string was JUST for this post, not that you are using hard coded connection strings all over the place - (don't do that!!!).
And you tagged this as asp.net so we assuem this is a web page, right?
Thus, this "air code" should suffice:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GetEmpList();
}
private void imtired_Click(object sender, EventArgs e)
{
int id = int.Parse(idbox.Text);
SqlCommand c = new SqlCommand("ughh");
c.Parameters.Add("#ID", SqlDbType.Int).Value = id;
c.Parameters.Add("#fname", SqlDbType.NVarChar).Value = fnametxt.Text;
c.Parameters.Add("#lname", SqlDbType.NVarChar).Value = lnametxt.Text;
MyRstP(c, false);
MessageBox.Show("Successfully inserted");
}
void GetEmpList()
{
SqlCommand c = new SqlCommand("Listughh");
DataTable dt = new DataTable();
DataGridView1.DataSource = MyRstP(c);
DataGridView1.DataBind();
}
public DataTable MyRstP(SqlCommand cmdSQL, bool returnData = true)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
cmdSQL.CommandType = CommandType.StoredProcedure;
if (returnData)
{
rstData.Load(cmdSQL.ExecuteReader());
}
else
{
cmdSQL.ExecuteNonQuery();
}
}
}
return rstData;
}
And as for that file in use.
Reboot your computer.
So, "isolate" your connection routine(s). Don't attempt to persist the connection at the form/class level, move your connection string to config or settings. (and bonus points is you can use the connection builder).

error message in oledbcommand.executenonquery();

I wrote the following program in C#
I have no problem when inserting information in the database
But when deleting information and during debugging, it gets an error on the following
line
cmd.executenonquery();
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.OleDb;
namespace _01_AccessTestDB
{
public partial class frmUser : Form
{
public frmUser()
{
InitializeComponent();
}
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=TestDB.accdb");
OleDbCommand cmd = new OleDbCommand();
void display()
{
DataSet ds = new DataSet();
OleDbDataAdapter adp = new OleDbDataAdapter();
cmd.CommandType = CommandType.Text;
adp.SelectCommand=new OleDbCommand();
adp.SelectCommand.Connection= con;
adp.SelectCommand.CommandText="select * from TBLUser";
adp.Fill(ds, "TBLUser");
dgvUser.DataSource=ds;
dgvUser.DataMember=("TBLUser");
dgvUser.Columns[0].HeaderText="کد";
dgvUser.Columns[1].HeaderText="نام کاربری";
dgvUser.Columns[2].HeaderText="کلمه عبور";
}
private void frmUser_Load(object sender, EventArgs e)
{
display();
}
private void btnSave_Click(object sender, EventArgs e)
{
cmd.Parameters.Clear();
cmd.Connection = con;
con.Open();
cmd.CommandText="insert into TBLUser(ID,UserN,Pass)values(#a,#b,#c)";
cmd.Parameters.AddWithValue("#a", txtCode.Text);
cmd.Parameters.AddWithValue("#b", txtUser.Text);
cmd.Parameters.AddWithValue("#c", txtPass.Text);
cmd.ExecuteNonQuery();
con.Close();
string message, title;
title="تعریف کاربران";
message="اطلاعات جدید با موفقیت ثبت گردید";
MessageBox.Show(message, title, MessageBoxButtons.OK,
MessageBoxIcon.Information);
txtCode.Clear();
txtUser.Clear();
txtPass.Clear();
display();
}
The program is running correctly so far, but it encountered a problem in the data deletion section
private void btnDelet_Click(object sender, EventArgs e)
{
int h = Convert.ToInt32(dgvUser.SelectedCells[0].Value);
cmd.Parameters.Clear();
cmd.Connection=con;
cmd.CommandText="delet from TBLUser Where ID=#N";
cmd.Parameters.AddWithValue("#N", h);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
string message, title;
title="تعریف کاربران";
message="اطلاعات حذف گردید";
MessageBox.Show(message, title, MessageBoxButtons.OK,
MessageBoxIcon.Information);
display();
}
}
}
Change from
cmd.CommandText="delet from TBLUser Where ID=#N";
To
cmd.CommandText="delete from TBLUser Where ID=#N";
Also follow #user18387401 recommendations
In regards to cmd.Parameters.AddWithValue, use cmd.Parameters.Add instead.
Edit
Here is a model to use for removing a record use SQL-Server in .NET Core. Since you are using Access the connection and command change to OleDb. So don't copy-n-paste this code, adapt to your current code. The Remove method should reside in a separate class but can reside in the form.
Best to add in a BindingSource, this way cast someBindingSource.Current to whatever the current row in the DataGridView is e.g. if the source is a DataTable use ((DataRow)someBindingSource.Current).Row.Field... to get the primary key to use for deleting. Once the record is removed use someBindingSource.RemoveCurrent() to remove the record from your DataGridView.
public static (bool success, Exception exception) Remove(int identifier)
{
using var cn = new SqlConnection("TODO");
using var cmd = new SqlCommand
{
Connection = cn,
CommandText = "DELETE FROM TBLUser WHERE Id = #Identifier;"
};
try
{
cn.Open();
cmd.Parameters.Add("#Identifier", SqlDbType.Int).Value = identifier;
cmd.ExecuteNonQuery();
return (true, null);
}
catch (Exception localException)
{
return (false, localException);
}
}
Usage in your form (DataOperations is a separate class)
var (success, exception) = DataOperations.Remove(identifier);
if (success)
{
// record removed
}
else
{
// deal with exception using exception variable
}

Passing updates back to sql server from a datagrid viewer

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

method is not being called by application

My method is not being called by my application. I've used breakpoints and it's never initiated in the code. I'm building a C# Windows Forms application using an Azure Database, but the DataGridView is never being filled neither is the code being called at all... I have noooo clue whatsoever why..
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.Configuration;
namespace MyWinFormsProj
{
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
}
//Connection String
string cs = ConfigurationManager.ConnectionStrings
["MyConnetion"].ConnectionString;
// Load all employees
private void dataEmployees_Load()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
// Crate company
private void createCompany_Click_1(object sender, EventArgs e)
{
if (textBoxCompanyName.Text == "")
{
MessageBox.Show("Fill out information");
return;
}
using (SqlConnection con = new SqlConnection(cs))
{
//Create SqlConnection
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.Company (companyName)
values(#companyName)", con);
cmd.Parameters.AddWithValue(
"#companyName", textBoxCompanyName.Text);
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
MessageBox.Show("Grattis! Du har skapat ett företag");
}
}
}
}
The second method is working and is doing what it is supposed to do, but the first one is never called..
you need to set an event handler on the gridView onLoad and pass this method to the handler
public void GridView_OnLoad(object sender, EventArgs e)
{
dataEmployees_Load();
}
You need to fix your method signature to look like this:
private void dataEmployees_Load(object sender, EventArgs e)
Then, in your GirdView, you need to set this function as handler for event "onload":
OnLoad="dataEmployees_Load"
Thank you guys for your answers it helped my solve the problem. Like you were saying the problem was in the method not being called. So I called it directly on initiliazeComponent like this.
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
Load += new EventHandler(dataEmployees_Load); //Added this code
}
// Load all employees
private void dataEmployees_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}

Categories