我发现了一个使用gridview 的奇怪情况。
在gridview上选择一个标题行,应该选择数据字段并将它们传递给允许编辑以更新记录或删除记录的Winform字段。
显然,相同的代码会产生不同的结果。
知道发生了什么以及如何纠正这种情况吗?
谢谢你。
工作代码:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace InsertUpdateDeleteDemo
{
public partial class frmMain : Form
{
string cs = "Data Source=.;Initial Catalog=Sample;Integrated Security=true;";
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
//ID variable used in Updating and Deleting Record
int ID = 0;
DataTable dt;
public frmMain()
{
InitializeComponent();
DisplayData();
}
private void txt_SearchName_TextChanged(object sender, EventArgs e)
{
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select * from tbl_Employee where FirstName like '" + txt_SearchName.Text + "%'", con);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
ClearData();
}
//Insert Data
private void btn_Insert_Click(object sender, EventArgs e)
{
if (txt_First_Name.Text != "" && txt_Last_Name.Text != "" && txt_State.Text != "")
{
txt_SearchName.Text = "";
cmd = new SqlCommand("insert into tbl_Employee(FirstName,LastName,State) values(@FirstName,@state)", con);
con.Open();
cmd.Parameters.AddWithValue("@FirstName", txt_First_Name.Text);
cmd.Parameters.AddWithValue("@LastName", txt_Last_Name.Text);
cmd.Parameters.AddWithValue("@state", txt_State.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
ClearData();
DisplayData();
}
else
{
MessageBox.Show("Please Provide Details!");
}
}
//Display Data in DataGridView
private void DisplayData()
{
con.Open();
DataTable dt=new DataTable();
adapt=new SqlDataAdapter("select * from tbl_Employee",con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
//Clear Data
private void ClearData()
{
txt_First_Name.Text = "";
txt_Last_Name.Text = "";
txt_State.Text = "";
ID = 0;
}
//dataGridView1 RowHeaderMouseClick Event
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txt_First_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txt_Last_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
txt_State.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
}
//Update Record
private void btn_Update_Click(object sender, EventArgs e)
{
if (txt_First_Name.Text != "" && txt_State.Text != "")
{
cmd = new SqlCommand("update tbl_Employee set FirstName=@FirstName,LastName=@LastName,State=@state where ID=@id", con);
con.Open();
cmd.Parameters.AddWithValue("@id", ID);
cmd.Parameters.AddWithValue("@FirstName", txt_First_Name.Text);
cmd.Parameters.AddWithValue("@LastName", txt_Last_Name.Text);
cmd.Parameters.AddWithValue("@state", txt_State.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Update");
}
}
//Delete Record
private void btn_Delete_Click(object sender, EventArgs e)
{
if(ID!=0)
{
cmd = new SqlCommand("delete tbl_Employee 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");
}
}
private void frmMain_Load(object sender, EventArgs e)
{
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select * from tbl_Employee", con);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void txt_First_Name_TextChanged(object sender, EventArgs e)
{
}
private void txt_Last_Name_TextChanged(object sender, EventArgs e)
{
}
private void txt_State_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
}
}
两段相似的代码。在第一个视图中,一个有效,另一个无效。
单击 gridview 标题行时,不会选择数据并将其传递到 Winform 字段。
任何提示为什么?
非工作代码:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Banco_de_Imagens_Beatriz
{
public partial class EcranDiagnostico : Form
{
string cs = "Data Source=Posto0;Initial Catalog=Banco_Imagens;Persist Security Info=True;User ID=sa;Password=12QWaszx";
SqlConnection con = new SqlConnection("Data Source=Posto0;Initial Catalog=Banco_Imagens;Persist Security Info=True;User ID=sa;Password=12QWaszx");
SqlCommand cmd;
SqlDataAdapter adapt;
//ID variable used in Updating and Deleting Record
int iddiag = 0;
DataTable dt;
public EcranDiagnostico()
{
InitializeComponent();
DisplayData();
}
private void txt_SearchName_TextChanged(object sender, EventArgs e)
{
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select * from tb_diag where nome_diag like '" + txt_SearchName.Text + "%'", con);
dt = new DataTable();
adapt.Fill(dt);
DataGridView1.DataSource = dt;
con.Close();
ClearData();
}
//Insert Data
private void btn_Insert_Click(object sender, EventArgs e)
{
if (txt_NomeDiag.Text != "" && txt_DescrDiag.Text != "")
{
txt_SearchName.Text = "";
cmd = new SqlCommand("insert into tb_diag(nome_diag,descr_diag) values(@nome_diag,@descr_diag)", con);
con.Open();
cmd.Parameters.AddWithValue("@nome_diag", txt_NomeDiag.Text);
cmd.Parameters.AddWithValue("@descr_diag", txt_DescrDiag.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Registo inserido com sucesso.");
ClearData();
DisplayData();
}
else
{
MessageBox.Show("Não introduziu dados. Introduza os dados que pretende.");
}
}
//Display Data in DataGridView
private void DisplayData()
{
con.Open();
DataTable dt = new DataTable();
adapt = new SqlDataAdapter("select * from tb_diag", con);
adapt.Fill(dt);
DataGridView1.DataSource = dt;
con.Close();
}
//Clear Data
private void ClearData()
{
txt_NomeDiag.Text = "";
txt_DescrDiag.Text = "";
iddiag = 0;
}
//dataGridView1 RowHeaderMouseClick Event
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
iddiag = Convert.ToInt32(DataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txt_NomeDiag.Text = DataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txt_DescrDiag.Text = DataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
}
//Update Record
private void btn_Update_Click(object sender, EventArgs e)
{
if (txt_NomeDiag.Text != "" && txt_DescrDiag.Text != "")
{
cmd = new SqlCommand("update tb_diag set nome_diag=@nome_diag,descr_diag=@descr_diag where iddiag=@iddiag", con);
con.Open();
cmd.Parameters.AddWithValue("@iddiag", iddiag);
cmd.Parameters.AddWithValue("@nome_diag", txt_NomeDiag.Text);
cmd.Parameters.AddWithValue("@descr_diag", txt_DescrDiag.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Registo actualizado com sucesso.");
con.Close();
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Não seleccionou nenhum registo. Seleccione o registo a actualizarr.");
}
}
//Delete Record
private void btn_Delete_Click(object sender, EventArgs e)
{
if (iddiag != 0)
{
cmd = new SqlCommand("delete tb_diag where iddiag=@iddiag", con);
con.Open();
cmd.Parameters.AddWithValue("@iddiag", iddiag);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Registo eliminado com sucesso.");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Não seleccionou nenhum registo. Seleccione o registo a eliminar");
}
}
private void EcranDiagnostico_Load(object sender, EventArgs e)
{
// TODO: esta linha de código carrega dados na tabela 'dataSet_Tabela_Diagnostico.tb_diag'. Você pode movê-la ou removê-la conforme necessário.
//this.tb_diagTableAdapter.Fill(this.dataSet_Tabela_Diagnostico.tb_diag);
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select * from tb_diag", con);
dt = new DataTable();
adapt.Fill(dt);
DataGridView1.DataSource = dt;
con.Close();
}
private void txt_NomeDiag_TextChanged(object sender, EventArgs e)
{
}
private void txt_DescrDiag_TextChanged(object sender, EventArgs e)
{
}
}
}