0
在我的Windows窗體應用程序我已經加入DataGridViewLinkColumn
特定行的delete
記錄,每當我點擊Delete
LinkLabel的和做這個我已經加入dataGridView1_CellContentClick
事件象下面這樣:dataGridView1_CellContentClick事件在C#中的WinForms不火
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;
namespace search
{
public partial class Form1 : Form
{
SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Documents and Settings\\Musewerx\\My Documents\\Contacts.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
public Form1()
{
InitializeComponent();
}
public void bindDatagridview()
{
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = new SqlCommand("Select * from contactsinfo", connection);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.AutoGenerateColumns = false;
dataGridView1.AllowUserToAddRows = false;
clear();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
string contactname = this.dataGridView1.Rows[e.RowIndex].Cells["ContactName"].Value.ToString();
string contactnumber = this.dataGridView1.Rows[e.RowIndex].Cells["ContactNumber"].Value.ToString();
if (e.ColumnIndex == 3)
{
da.DeleteCommand = new SqlCommand("Delete from contactsinfo where ContactName = '" + contactname.ToString() + "', and ContactNumber ='" + contactnumber.ToString() + "'", connection);
connection.Open();
da.DeleteCommand.ExecuteNonQuery();
connection.Close();
}
}
public void clear()
{
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == string.Empty)
{
MessageBox.Show("Enter Contact Name");
}
else if(textBox2.Text == string.Empty)
{
MessageBox.Show("Enter Contact Number");
}
else
{
da.InsertCommand = new SqlCommand("Insert into contactsinfo(ContactName,ContactNumber) Values('" + textBox1.Text + "','" + textBox2.Text + "')", connection);
connection.Open();
da.InsertCommand.ExecuteNonQuery();
bindDatagridview();
clear();
connection.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
this.Hide();
}
private void Form1_Load(object sender, EventArgs e)
{
bindDatagridview();
DataGridViewLinkColumn dgvLink = new DataGridViewLinkColumn();
dgvLink.UseColumnTextForLinkValue = true;
dgvLink.LinkBehavior = LinkBehavior.SystemDefault;
dgvLink.HeaderText = "Delete";
dgvLink.Name = "lnk_delete";
dgvLink.LinkColor = Color.Blue;
dgvLink.TrackVisitedState = true;
dgvLink.Text = "Delete";
bool check = dataGridView1.Columns.Contains("lnk_delete");
if (check == false)
{
dataGridView1.Columns.Add(dgvLink);
}
}
}
}
但是當我點擊Delete
linklabel時,它不會進入dataGridView1_CellContentClick
事件。 請建議我,等待您的回覆。 謝謝。