如何根据dataGridView中的另一个列值自定义DataGridViewButton单元格

时间:2019-02-17 03:51:20

标签: c# sql-server

我创建了一个DataGridView,然后在编码中手动为其检索数据。另外,我添加了一个DataGridViewButtonCell,它工作正常。但是我想根据另一列(状态列索引为4)的值对其进行自定义。

例如
-如果“状态列”的值为“新建”,则希望显示form1
-如果“状态列”的值为“打开”,则希望显示form2
-如果“状态列”的值为“已分配”,则希望显示form3
-如果“状态列”的值是“重复”,“推迟”和“重复”想要显示form4

如何执行此过程?这是数据网格视图的图像

![1]:https:C:\ Users \ kularathna \ Desktop \ New.PNG

这是用于将数据检索到dataGridView的代码

package atm;
import java.util.Scanner;

public class ATM { 
    public static void main(String[] args)
    {
        int a, b, c, d;

        a = 20;
        b = 10;
        c = 5;
        d = 1;

        Scanner user_input = new Scanner(System.in);
        double withdraw;

        System.out.print("Put an amount of \u0024 to withdraw: ");
        withdraw = user_input.nextDouble();

        System.out.println(withdraw / a);
        System.out.println("Amount is \u0024 " + withdraw);

        user_input.close();
    }
}

我尝试使用
 if(senderGrid [e.ColumnIndex,e.RowIndex]是DataGridViewTextBoxCell.Value =“ New”)行
但不起作用

1 个答案:

答案 0 :(得分:0)

在您共享的代码中也有构建错误和逻辑错误。

您将数据表绑定到GridView,并将一个ButtonColumn添加到GridView。单击该列上的按钮时,您要基于“状态”列的值显示不同的表单。

在您的代码中,您尝试比较ButtonColumn的值。 ButtonColumn没有任何值,因为它没有绑定到DataTable中的任何列。

您需要获取GridView的“状态”列的值,然后比较其值。

您需要在CellContentClick事件处理程序中包含以下代码。该代码是示例代码。您需要根据需要进行更改。

private void dgvTester_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
    try
    {
        var senderGrid = (DataGridView)sender;
        if (senderGrid[e.ColumnIndex, e.RowIndex] is DataGridViewButtonCell)
        {
             // "3" in following `if` condition is the column index of "Status" column.
             // You need to put appropriate column index here.
               var selectedStatus = senderGrid[3, e.RowIndex].Value.ToString();
                if (selectedStatus  == "New")
                {
                    MessageBox.Show("New");
                }
                else if (selectedStatus == "Open")
                {
                    MessageBox.Show("Open");
                }
                else if (selectedStatus == "Assigned")
                {
                    MessageBox.Show("Assigned");
                }
                else if (selectedStatus == "Duplicate")
                {
                    MessageBox.Show("Duplicate");
                }
         }
     }
     catch (Exception error)
     {
         MessageBox.Show(error + "Invalid");
     }
 }

这应该可以帮助您解决问题。