如何替换文本值上的单元格内容?

时间:2017-08-03 20:58:20

标签: c# c#-4.0 datagridview

我使用DataGridView。它在一列中的内容按钮:

Button cellButton = new Button();
clicked.  Here I'm just storing the row index.
cellButton.Tag = e.RowIndex;
cellButton.Text = "Выдать код";
cellButton.Click += new EventHandler((s, seder) => {
   string result = lnkSynEvent_Click(s, e, id);
   dataGridView1[e.ColumnIndex, e.RowIndex].Value = result;
   cellButton.Enabled = false;
   cellButton.Text = result;
});

点击后如何在功能中替换文本值上的按钮:

new EventHandler((s, seder) => { // Here });

我试过了:

cellButton.Click += new EventHandler((s, seder) => {

      string result = lnkSynEvent_Click(s, e, id);

      dataGridView1.Rows[e.RowIndex].Cells[2] = new DataGridViewTextBoxCell();
      dataGridView1.Rows[e.RowIndex].Cells[2].Value = result;

});

1 个答案:

答案 0 :(得分:2)

如果我理解你的要求,这可以帮助你开始:

using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {

        DataGridView dgv = new DataGridView();
        BindingList<dgvitem> itemsList = new BindingList<dgvitem>();

        public Form1()
        {
            InitializeComponent();
            InitializeTheDGV();
            itemsList.Add(new dgvitem { JustaTextField = "aksldjf sadfjasifuqw adsfasf" });
            itemsList.Add(new dgvitem { JustaTextField = "qwerioqu aisdfnvmz, oaa" });
        }

        private void InitializeTheDGV()
        {
            dgv.Location = new Point(this.Location.X + 5, this.Location.Y + 5);
            dgv.DataSource = itemsList;
            dgv.AutoGenerateColumns = false;
            this.Controls.Add(dgv);
            dgv.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "My col header", Name = "mycol1" });
            dgv.Columns.Add(new DataGridViewButtonColumn() { HeaderText = "click in this column", Name = "mycol2" });
            dgv.Columns["mycol1"].DataPropertyName = "JustaTextField";
            dgv.CellContentClick += Dgv_CellContentClick;
        }

        private void Dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (!(sender is DataGridView))
            {
                return;
            }
            dgv.Rows[e.RowIndex].Cells[1] = new DataGridViewTextBoxCell();
            dgv.Rows[e.RowIndex].Cells[1].Value = "put some text in here";
        }
    }


    public class dgvitem
    {
        public string JustaTextField { get; set; }
    }
}