在C#中使用GridView控制单元格按钮 [英] Handle Cell Button in GridView in C#

查看:118
本文介绍了在C#中使用GridView控制单元格按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#项目中工作,我创建了一个 GridView ,并且我已经在一列中创建了一个 Button 。当我按下按钮时,我想打开对话框窗体,当我按下它时,实验代码如下所示:

pre $ data $ data $ data $ data (e.RowIndex> = 0&((DataGridView)sender).Columns [e.ColumnIndex] .GetType()== typeof( DataGridViewButtonColumn))
{
// TODO - 这里执行代码
MessageBox.Show(我按了CellButton);


$ / code>

然后调用CellContentClick我做了这段代码:

  public void showCourse()
{
SqlCommand com = new SqlCommand(@SELECT [Course_ID]
,[CourseCreated]。[CourseCreated_Name]
,[CourseCreated]。[CourseCreated_Type]
,[Course_Hours]
,[Course_Duration]
,[Course_Place]
,[Trainer_Info]。[Trainer_Name]
FROM [VolunteersAffairs]。[dbo]。[Course_Info],[CourseCreated],[Trainer_Info]
其中[Course_Info]。[CourseCreated_ID] = [CourseCreated]。[ CourseCreated_ID]和[T​​rainer_Info]。[Trainer_ID] = [Course_Info]。[T rainer_ID],con);
SqlDataAdapter da = new SqlDataAdapter();
DataSet dats = new DataSet();
da.SelectCommand = com;
da.Fill(dats,Course_Info);
dataGridViewShowCourse.DataSource = null;
dataGridViewShowCourse.Columns.Clear();
dataGridViewShowCourse.DataSource = dats.Tables [Course_Info];
DataGridViewButtonColumn col = new DataGridViewButtonColumn();
col.UseColumnTextForButtonValue = true;
col.Text =添加;
col.Name =stedents;
col.HeaderText =Got Course;
dataGridViewShowCourse.Columns.Add(col);
//这里是我的事件处理程序
dataGridViewShowCourse.CellContentClick + = new DataGridViewCellEventHandler(dataGridViewShowCourse_CellContentClick);
}

当我第一次按下该按钮时, ,但问题是,当我添加一些行代码执行很多次,这意味着消息在添加任何行之前第一次出现一次,如果我再添加一行,消息会出现两次,三次...等。或者当我按第一行时,消息出现一次,第二行消息出现两次,第三行消息出现三次....等。



请告诉我错误在哪里。



注意:这里调用的函数 showCourse() / p>

  public AddCourses()
{
InitializeComponent();
showCourse();
FillComboBoxCourseName();
comboBoxCourseName.SelectedItem = null;
FillComboBoxTrainerName();
comboBoxTrainers.SelectedItem = null;

$ / code>

这里是我再次调用ShowCourse()的按钮

  private void buttonAddCourse_Click(object sender,EventArgs e)
{
try
{
CourseClass c =(CourseClass)comboBoxCourseName.SelectedItem;
// SqlCommand com = new SqlCommand(update Course_Info set Course_Hours = \'\'where Course_ID =+ c.ID,con);
SqlCommand com = new SqlCommand(@INSERT INTO [VolunteersAffairs]。[dbo]。[Course_Info]
([CourseCreated_ID]
,[Course_Hours]
,[Course_Duration]
,[Course_Place]
,[Trainer_ID])
VALUES
(@CourseCreatedID
,@ CourseHours
,@ CourseDuration
,@ CoursePlace
,@ TrainerID),con);
com.Parameters.Add(@ CourseCreatedID,SqlDbType.Int).Value =(comboBoxCourseName.SelectedItem as CourseClass).ID;
com.Parameters.Add(@ CourseHours,SqlDbType.NVarChar,50).Value = textBoxCourseHours.Text;
com.Parameters.Add(@ CourseDuration,SqlDbType.NVarChar,50).Value = textBoxCourseDuration.Text;
com.Parameters.Add(@ CoursePlace,SqlDbType.NVarChar,50).Value = textBoxCoursePlace.Text;
com.Parameters.Add(@ TrainerID,SqlDbType.Int).Value =(comboBoxTrainers.SelectedItem as CourseClass).ID;
con.Open();
com.ExecuteNonQuery();
con.Close();
showCourse(); //这里是函数
FillComboBoxCourseName();

catch(Exception ex)
{
if(con.State == ConnectionState.Open)
con.Close();
MessageBoxEx.Show(请再试一次,,MessageBoxButtons.OK,MessageBoxIcon.Asterisk);


$ b


解决方案

在您的事件处理程序代码中,您将重新分配事件处理程序......

  void dataGridViewShowCourse_CellContentClick(object发送者,DataGridViewCellEventArgs e)
{
//问题出现在这一行,重新将同一事件处理程序重新分配给同一个事件
//事件处理程序将执行多于一次的时间和数量每次执行的时间也会不断增加
dataGridViewShowCourse.CellContentClick = new DataGridViewCellEventHandler(dataGridViewShowCourse_CellContentClick);
//确保单击不在标题和列上的是ButtonColumn类型
if(e.RowIndex> = 0&((DataGridView)sender).Columns [e.ColumnIndex] .GetType ()== typeof(DataGridViewButtonColumn))
{
// TODO - 这里执行代码
MessageBox.Show(我按了CellButton);




$ b $ p
$ b

你在你的showCourse 方法,因此您不需要再次分配它。

  dataGridViewShowCourse.CellContentClick + = new DataGridViewCellEventHandler(dataGridViewShowCourse_CellContentClick); 

为了解决这个问题,您需要在下面的另一个函数中分配事件处理函数:

  public void showCellButton()
{
dataGridViewShowCourse.CellContentClick + = new DataGridViewCellEventHandler(dataGridViewShowCourse_CellContentClick);
}


I'm working in C# project, I made a GridView and I already made a Button in one column. When I press the Button I want to open Dialog form, I did experimental code showing a message when I press it, the experimental code as below:

    void dataGridViewShowCourse_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        //make sure click not on header and column is type of ButtonColumn
        if (e.RowIndex >= 0 && ((DataGridView)sender).Columns[e.ColumnIndex].GetType() == typeof(DataGridViewButtonColumn))
        {
             //TODO - Execute Code Here
            MessageBox.Show("I pressed CellButton");
        }
    }

And to call CellContentClick I did this code:

    public void showCourse()
    {
        SqlCommand com = new SqlCommand(@"SELECT [Course_ID]
                                              ,[CourseCreated].[CourseCreated_Name]
                                              ,[CourseCreated].[CourseCreated_Type]
                                              ,[Course_Hours]
                                              ,[Course_Duration]
                                              ,[Course_Place]
                                              ,[Trainer_Info].[Trainer_Name]
                                          FROM [VolunteersAffairs].[dbo].[Course_Info],[CourseCreated], [Trainer_Info]
                                          where [Course_Info].[CourseCreated_ID] = [CourseCreated].[CourseCreated_ID] and [Trainer_Info].[Trainer_ID] = [Course_Info].[Trainer_ID]", con);
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet dats = new DataSet();
        da.SelectCommand = com;
        da.Fill(dats, "Course_Info");
        dataGridViewShowCourse.DataSource = null;
        dataGridViewShowCourse.Columns.Clear();
        dataGridViewShowCourse.DataSource = dats.Tables["Course_Info"];
        DataGridViewButtonColumn col = new DataGridViewButtonColumn();
        col.UseColumnTextForButtonValue = true;
        col.Text = "ِِAdd";
        col.Name = "stedents";
        col.HeaderText = "Got Course";
        dataGridViewShowCourse.Columns.Add(col);
        //Here is my Event Handler
        dataGridViewShowCourse.CellContentClick += new DataGridViewCellEventHandler(dataGridViewShowCourse_CellContentClick);
    }

When I press that button for first time every thing is worked fine, But the problem is that when I add some rows the code executed many times, meant that the message appears one time for first time before adding any row, and if I add one more row the message appears twice, three times...etc. Or when I press the first row the message appears one time, second row the message appears twice, third row the message appears three time....etc.

Please tell me me where is the error.

Note* the function showCourse() called here:

    public AddCourses()
    {
        InitializeComponent();
        showCourse();
        FillComboBoxCourseName();
        comboBoxCourseName.SelectedItem = null;
        FillComboBoxTrainerName();
        comboBoxTrainers.SelectedItem = null;
    }

And here is the button where I call again the ShowCourse()

private void buttonAddCourse_Click(object sender, EventArgs e)
    {
        try
        {
            CourseClass c = (CourseClass)comboBoxCourseName.SelectedItem;
            //SqlCommand com = new SqlCommand("update Course_Info set Course_Hours=\' \'where Course_ID = " + c.ID, con);
            SqlCommand com = new SqlCommand(@"INSERT INTO [VolunteersAffairs].[dbo].[Course_Info]
                                                       ([CourseCreated_ID]
                                                       ,[Course_Hours]
                                                       ,[Course_Duration]
                                                       ,[Course_Place]
                                                       ,[Trainer_ID])
                                                 VALUES
                                                       (@CourseCreatedID
                                                       ,@CourseHours
                                                       ,@CourseDuration
                                                       ,@CoursePlace
                                                       ,@TrainerID)", con);
            com.Parameters.Add("@CourseCreatedID", SqlDbType.Int).Value = (comboBoxCourseName.SelectedItem as CourseClass).ID;
            com.Parameters.Add("@CourseHours", SqlDbType.NVarChar, 50).Value = textBoxCourseHours.Text;
            com.Parameters.Add("@CourseDuration", SqlDbType.NVarChar, 50).Value = textBoxCourseDuration.Text;
            com.Parameters.Add("@CoursePlace", SqlDbType.NVarChar, 50).Value = textBoxCoursePlace.Text;
            com.Parameters.Add("@TrainerID", SqlDbType.Int).Value = (comboBoxTrainers.SelectedItem as CourseClass).ID;
            con.Open();
            com.ExecuteNonQuery();
            con.Close();
            showCourse(); // Here is the Function
            FillComboBoxCourseName();
        }
        catch (Exception ex)
        {
            if (con.State == ConnectionState.Open)
                con.Close();
            MessageBoxEx.Show("Please Try Again", "", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

        }
    }

解决方案

In your event handler code you are re-assigning the event handler again and again...

void dataGridViewShowCourse_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        // Problem is in this line, re-assigning the same event handler again to the same event
        // event handler will execute more than 1 time and number of execution will also keep increasing each time
        dataGridViewShowCourse.CellContentClick += new DataGridViewCellEventHandler(dataGridViewShowCourse_CellContentClick);
        //make sure click not on header and column is type of ButtonColumn
        if (e.RowIndex >= 0 && ((DataGridView)sender).Columns[e.ColumnIndex].GetType() == typeof(DataGridViewButtonColumn))
        {
             //TODO - Execute Code Here
            MessageBox.Show("I pressed CellButton");
        }
    }

you have the following line of code in your "showCourse" method, therefore you don't need to assign it again

dataGridViewShowCourse.CellContentClick += new DataGridViewCellEventHandler(dataGridViewShowCourse_CellContentClick);

To solve the problem you need to assign the event handler in another function as below

public void showCellButton()
    {
        dataGridViewShowCourse.CellContentClick += new DataGridViewCellEventHandler(dataGridViewShowCourse_CellContentClick);
    }

这篇关于在C#中使用GridView控制单元格按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆