当您运行说:
时,这是我的代码和错误消息System.Data.SqlClient.SqlException类型的未处理异常 发生在System.Data.dll
中
就此da.fill(dt);
SqlConnection con = new SqlConnection("Data Source=ANTONIANGGA-PC\\SQLEXPRESS;Initial Catalog=FullandStarving;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
public FormProduksi()
{
InitializeComponent();
showgridview();
}
private void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure; done :D
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
showgridview();
clear();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
答案 0 :(得分:3)
您正在关闭连接
con.Close();
然后使用
da.Fill(dt);
只需交换这一行:
showgridview();
con.Close();
注意:
Yoy应该使用参数化查询,以避免SQL Injection attacks:
var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);
将SqlConnection
和SqlCommand
包裹到using
中,以便那些人使用的资源disposed:
string position;
using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
con.Open();
using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con))
{
cmd.Parameters.AddWithValue("@id", id.Text);
var name = cmd.ExecuteScalar();
if (name != null)
{
position = name.ToString();
Response.Write("User Registration successful");
}
else
{
Console.WriteLine("No Employee found.");
}
}
}
答案 1 :(得分:2)
只需更改showgridview()
功能,如下所示连接已打开&正确关闭。
同时检查您的SQL查询,提供空间并维护查询语法:
SELECT * FROM Produksi
将这些行注释为以下代码:
void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure;
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
然后你不会遇到连接问题和错误。
按钮点击代码更改关闭连接,如下所示:
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try
{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
con.Close();
showgridview();
clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
另外,进一步阅读: