无法添加行C#DataGridView

时间:2017-10-10 04:48:08

标签: c# .net winforms datagridview

我正在研究这个小C#项目,我需要将数据添加到DataGridView控件。我以前工作过,但遗憾的是,因为我对我的代码做了一些修改,我不记得以前我是怎么做的。我记得的是,在VisualStudio中我回到Form.Designer.cs并在测试之前将一些控件更改为public static,这样我就可以添加行了。我在网上阅读了一些关于这一点的内容,他们建议不这样做,这就是我改变代码的原因。

无论如何前进,我有主要的AutoCheck.cs类,它有方法:

public void addNASDestination(string[] info){
        /*string[0] = Name
        * string[1] = Path
        * string[2] = Username
        * string[3] = Password - Needs to be passed to XML encrypted. Not displayed in the table at all
        */
        destinationsTable.Rows.Add(info[0], "NAS", info[1], info[2], info[3]);
        destinationsTable.Update();
        destinationsTable.Refresh();
        checkTableRowCount();
    }

public void addBDRDestination(string[] info){
        /*string[0] = Name
        * string[1] = Path
        */
        destinationsTable.Rows.Add(info[0], "BDR", info[1]);
        //destinationsTable.Update();
        //destinationsTable.Refresh();
        checkTableRowCount();
    }

这些方法曾经用于向DataGridView添加行。 info数组值从方法中的另一个名为AddDialog.cs的类传递:

private void destAddButton_Click(object sender, EventArgs e)
    {
        ac = new AutoCheck();
        if(destNameTextbox.TextLength <= 0 || destNameTextbox.Text == null){
            MessageBox.Show("Please enter a name","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
        }else if(destPathTextbox.TextLength <= 0 || destPathTextbox.Text == null){
            MessageBox.Show("Please select a path", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }else if (!Directory.Exists(destPathTextbox.Text)){
            MessageBox.Show("Please select a valid path", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }else if (isNAS())
        {
            if((destUserTextbox.TextLength <= 0 || destUserTextbox.Text == null) || (destPassTextbox.TextLength <= 0 || destPassTextbox.Text == null)){
                MessageBox.Show("Please enter a Username and Password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }else{
                //If Name and User/Pass are good, add info to temp array and pass by reference to addNASDestination
                string[] temp = new string[] { destNameTextbox.Text, destPathTextbox.Text, destUserTextbox.Text, AutoCheck.Encrypt(destPassTextbox.Text) };
                ac.addNASDestination(temp);
                this.Dispose();
            }
        }else{
            //Assume its a BDR and add info to temp array and pass by reference to addBDRDestination
            string[] temp = new string[] {destNameTextbox.Text,destPathTextbox.Text};
            ac.addBDRDestination(temp);
            this.Dispose();
        }
    }

AddDialog正如名称所描述的那样,一个对话框要求用户输入,然后抓取输入并将其放入数组中,通过引用传递数组addBDRDestination或{{1并且他们应该将新行添加到addNASDestination

这对我不起作用,我试图通过使用DataGridView来查看数据是否被发送到addBDRDestinationaddNASDestination以输出正在传递的数据到达那些方法,但没有添加新行。

我尝试通过添加此内容来刷新Console.WriteLine(这仍然是我发布的代码):

DataGridView

我也尝试了这个教程:http://csharp.net-informations.com/datagridview/csharp-datagridview-add-column.htm 它和我现在正在做的一样,但它增加了整个阵列,而不是像我一样打破它。

我还尝试创建destinationsTable.Update(); destinationsTable.Refresh(); ,如下所示:https://social.msdn.microsoft.com/Forums/windows/en-US/f12158b3-4510-47cb-b152-409489c3a51a/how-to-add-rows-in-datagridview-programmatically?forum=winformsdatacontrols

DataRow

我尝试启用和停用DataRow dr = this.dt.NewRow(); dr["a"] = "ax"; dr["b"] = "add item"; destinationsTable.Rows.Add(dr); ,但这没有效果。

我也试过这个:

AllowUserToAddRows

我不太确定我能尝试什么,因为这对我有用,现在不是。

我认为值得一提的是DataGridViewRow row = (DataGridViewRow)destinationsTable.Rows[0].Clone(); row.Cells[0].Value = info[0]; row.Cells[1].Value = "BDR"; row.Cells[2].Value = info[1]; destinationsTable.Rows.Add(row); AddDialog.cs是不同的类/源文件,但它们位于同一个命名空间AutoCheck.cs

AutoCheck我通过添加AddDialog.cs来访问AutoCheck.cs中的方法。 AutoCheck ac = new AutoCheck();AutoCheck也是如此。

还有其他方法可以添加行吗?或者我现在的代码做错了什么?非常感谢!

1 个答案:

答案 0 :(得分:0)

我不确定你面临的问题是什么:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            dgv.Columns.Add("cell_one", "Cell 1");
            dgv.Columns.Add("cell_two", "Cell 2");
            dgv.Columns.Add("cell_three", "Cell 3");
            dgv.Columns.Add("cell_four", "Cell 4");
            dgv.Columns.Add("cell_five", "Cell 5");
            addNASDestination(new string[] { "1", "3", "4", "5" });
        }

        public void addNASDestination(string[] info)
        {
            /*string[0] = Name
            * string[1] = Path
            * string[2] = Username
            * string[3] = Password - Needs to be passed to XML encrypted. Not displayed in the table at all
            */
            dgv.Rows.Add(info[0], "NAS", info[1], info[2], info[3]);
            //checkTableRowCount();
        }
    }

它按预期编译和工作。

即便如此:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            DataTable dt = new DataTable("main");
            dt.Columns.Add("column_one", typeof(string));
            dt.Columns.Add("column_two", typeof(string));
            dt.Columns.Add("column_three", typeof(string));
            dt.Columns.Add("column_four", typeof(string));
            dt.Columns.Add("column_five", typeof(string));
            dgv.DataSource = dt;
            addAnyRow();
        }

        public void addAnyRow() {
            var dt = (DataTable)dgv.DataSource;
            var row = dt.NewRow();
            row["column_one"] = "1";
            row["column_two"] = "2";
            row["column_three"] = "3";
            row["column_four"] = "4";
            row["column_five"] = "5";
            dt.Rows.Add(row);
    }
}

我把它们分开了:

namespace StackOverflow___46658777
{
    public static class Global
    {
        public static DataGridView DestinationTable;
    }

    public partial class Form1 : Form
    {
        public Form1(bool dataTableOrManual = false)
        {
            InitializeComponent();
            Global.DestinationTable = dgv;

            if (dataTableOrManual) {
                var dt = new DataTable("main");
                dt.Columns.Add("column_one", typeof(string));
                dt.Columns.Add("column_two", typeof(string));
                dt.Columns.Add("column_three", typeof(string));
                dt.Columns.Add("column_four", typeof(string));
                dt.Columns.Add("column_five", typeof(string));
                dgv.DataSource = dt;
                new TAutoCheck().AddAnyRow();
                new TAutoCheck().AddAnyRow();
                new TAutoCheck().AddAnyRow();
            } else {
                dgv.Columns.Add("cell_one", "Cell 1");
                dgv.Columns.Add("cell_two", "Cell 2");
                dgv.Columns.Add("cell_three", "Cell 3");
                dgv.Columns.Add("cell_four", "Cell 4");
                dgv.Columns.Add("cell_five", "Cell 5");
                new TAutoCheck().AddNASDestination(new string[] { "1", "3", "4", "5" });
            }
        }
    }

    public class TDialog : Form
    {
        public TDialog()
        {
            //anyButton.Click += validateRequest;
        }

        void validateRequest(object sender, EventArgs args)
        {
            new TAutoCheck().AddNASDestination(new string[] { "your", "validated", "strings", "are", "here" });
        }
    }

    public class TAutoCheck
    {
        public TAutoCheck() { }

        public void AddAnyRow()
        {
            var dt = (DataTable)Global.DestinationTable.DataSource;
            var row = dt.NewRow();
            row["column_one"] = "1";
            row["column_two"] = "2";
            row["column_three"] = "3";
            row["column_four"] = "4";
            row["column_five"] = "5";
            dt.Rows.Add(row);
        }

        public void AddNASDestination(string[] info)
        {
            /*string[0] = Name
            * string[1] = Path
            * string[2] = Username
            * string[3] = Password - Needs to be passed to XML encrypted. Not displayed in the table at all
            */
            Global.DestinationTable.Rows.Add(info[0], "NAS", info[1], info[2], info[3]);
            //checkTableRowCount();
        }
    }
}

按预期工作。我希望它与你分离它们的距离很近,因为你没有详细说明你的类和DataGridView之间的通信方式。在自己的源文件中分隔类不会改变内部类和函数的行为。