Datagridview列无法隐藏

时间:2015-06-18 17:34:44

标签: c# datagridview

我在datagridview上遇到问题隐藏列..

我不知道为什么我的代码不起作用..

这是我的代码..

private void kodeSatuanList()   // this one
{
         Connection.sqlConnection.Close();
         Connection.Connector(server, database, user, password);

        adapterKodeSatuan = new SqlDataAdapter(
             "SELECT ID,KOSAT,KETERANGAN FROM KOSAT", Connection.sqlConnection);
        dataTableKodeSatuan.Clear();
        dataGridView1.ClearSelection();
        adapterKodeSatuan.Fill(dataTableKodeSatuan);
        dataViewKodeSatuan = dataTableKodeSatuan.DefaultView;

        dataGridView1.ColumnCount = 3;

        dataGridView1.Columns[0].Visible = false; //this..column id, i set it false..
        dataGridView1.Columns[0].Name = "id";
        dataGridView1.Columns[0].HeaderText = "id";
        dataGridView1.Columns[0].DataPropertyName = "id";

        dataGridView1.Columns[1].Name = "Kode";
        dataGridView1.Columns[1].HeaderText = "Kode";
        dataGridView1.Columns[1].DataPropertyName = "kosat";

        dataGridView1.Columns[2].HeaderText = "Keterangan";
        dataGridView1.Columns[2].Name = "Keterangan";
        dataGridView1.Columns[2].DataPropertyName = "keterangan";

        dataGridView1.Columns[1].SortMode = DataGridViewColumnSortMode.Automatic;
        dataGridView1.Columns[2].SortMode = DataGridViewColumnSortMode.Automatic;

        dataGridView1.DataSource = dataViewKodeSatuan;
        Console.WriteLine("dataGridView1.Rows.Count = " + dataGridView1.Rows.Count);
        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true;
}   

根据我的代码......当我运行我的代码时......列“id”必须是不可见的。

请注意this video ..我录了它...... 或者从我的4shared中获取video

我仍然不知道我的问题,我仍然不知道我的代码有什么问题......旁边...... 我改变了我的代码,但是我没有使用SqlDataAdapter ..

private void kodeSatuanList()//this one
        {
            Connection.sqlConnection.Close();
            Connection.Connector(server, database, user, password);
            Connection.sqlCommand.Connection = Connection.sqlConnection;
            Connection.sqlCommand.CommandType = CommandType.Text;
            Connection.sqlCommand.CommandText = "SELECT ID,KOSAT,KETERANGAN FROM KOSAT";
            SqlDataReader kosatList = Connection.sqlCommand.ExecuteReader();
            while (kosatList.Read())
            {
                dataGridView1.Rows.Add(kosatList["ID"], kosatList["KOSAT"], kosatList["KETERANGAN"]);
            }
            Connection.sqlConnection.Close();


        //adapterKodeSatuan = new SqlDataAdapter("SELECT id,Kode,Keterangan FROM KOSAT", Connection.sqlConnection);
        //dataTableKodeSatuan.Clear();
        //dataGridView1.Columns.Clear();
        ////dataGridView1.ClearSelection();


        //dataGridView1.ColumnCount = 3;

        ////dataGridView1.Columns[0].Visible = false; //this..column id, i set it false..
        //dataGridView1.Columns[0].Name = "id";
        //dataGridView1.Columns[0].HeaderText = "id";
        //dataGridView1.Columns[0].DataPropertyName = "id";

        //dataGridView1.Columns[1].Name = "Kode";
        //dataGridView1.Columns[1].HeaderText = "Kode";
        //dataGridView1.Columns[1].DataPropertyName = "kosat";

        //dataGridView1.Columns[2].HeaderText = "Keterangan";
        //dataGridView1.Columns[2].Name = "Keterangan";
        //dataGridView1.Columns[2].DataPropertyName = "keterangan";

        //dataGridView1.Columns[1].SortMode = DataGridViewColumnSortMode.Automatic;
        //dataGridView1.Columns[2].SortMode = DataGridViewColumnSortMode.Automatic;

        //adapterKodeSatuan.Fill(dataTableKodeSatuan);
        //dataViewKodeSatuan = dataTableKodeSatuan.DefaultView;
        //dataGridView1.DataSource = dataViewKodeSatuan;
        ////dataGridView1.Columns[0].Visible = false;
        //Console.WriteLine("dataGridView1.Rows.Count = " + dataGridView1.Rows.Count);
        //dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true;

        //this.dataGridView1.Columns[0].Visible = false;


        //try
        //{
        //    Connection.Connector(server, database, user, password);
        //    listView1.Columns.Add("Kode", 70);
        //    listView1.Columns.Add("Keterangan", 140);
        //    //listView1.Items.Clear();
        //    adapterKodeSatuan = new SqlDataAdapter("SELECT * FROM KOSAT WHERE DELETEFLAG='N' ", Connection.sqlConnection);
        //    DataTable dt = new DataTable();
        //    adapterKodeSatuan.Fill(dt);
        //    ListViewItem listitem;
        //    Console.WriteLine("size = " + dt.Rows.Count);
        //    for (int i = 0; i < dt.Rows.Count; i++)
        //    {
        //        DataRow dr = dt.Rows[i];

        //        listitem = new ListViewItem();
        //        listitem.SubItems.Add( dr[0].ToString() );
        //        listitem.SubItems.Add( dr[1].ToString() );
        //        listitem.SubItems.Add( dr[2].ToString() );
        //        Console.WriteLine("aaa = " + dr[0].ToString());
        //        Console.WriteLine("bbb = " + dr[1].ToString());
        //        Console.WriteLine("ccc = " + dr[2].ToString());
        //        listView1.Items.Add(listitem);

        //    }

        //    listView1.Show();
        //}
        //catch (Exception ms) 
        //{
        //    Console.WriteLine("aaa");
        //}
    }        

这是我在kodeSatuan.cs中的代码

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 Microsoft.Win32;
using System.Data.SqlClient;

namespace belajarVariabelGlobal
{
    public partial class kodeSatuan : Form
    {
        public readonly static string server     = Registry.LocalMachine.OpenSubKey("Software\\Session", true).GetValue("server").ToString();
        public readonly static string database   = Registry.LocalMachine.OpenSubKey("Software\\Session", true).GetValue("database").ToString();
        public readonly static string user       = Registry.LocalMachine.OpenSubKey("Software\\Session", true).GetValue("user").ToString();
        public readonly static string password   = Registry.LocalMachine.OpenSubKey("Software\\Session", true).GetValue("pass").ToString();
        public static string kosat;
        public static string ket;
        SqlDataReader reader;
        SqlDataAdapter adapterKodeSatuan;
        DataTable dataTableKodeSatuan = new DataTable();
        DataView dataViewKodeSatuan = new DataView();
        public kodeSatuan()
        {
            InitializeComponent();

}

    private void kodeSatuanList()//this one
    {
        Connection.sqlConnection.Close();
        Connection.Connector(server, database, user, password);
        Connection.sqlCommand.Connection = Connection.sqlConnection;
        Connection.sqlCommand.CommandType = CommandType.Text;
        Connection.sqlCommand.CommandText = "SELECT ID,KOSAT,KETERANGAN FROM KOSAT";
        SqlDataReader kosatList = Connection.sqlCommand.ExecuteReader();
        while (kosatList.Read())
        {
            dataGridView1.Rows.Add(kosatList["ID"], kosatList["KOSAT"], kosatList["KETERANGAN"]);
        }
        Connection.sqlConnection.Close();


        //adapterKodeSatuan = new SqlDataAdapter("SELECT id,Kode,Keterangan FROM KOSAT", Connection.sqlConnection);
        //dataTableKodeSatuan.Clear();
        //dataGridView1.Columns.Clear();
        ////dataGridView1.ClearSelection();


        //dataGridView1.ColumnCount = 3;

        ////dataGridView1.Columns[0].Visible = false; //this..column id, i set it false..
        //dataGridView1.Columns[0].Name = "id";
        //dataGridView1.Columns[0].HeaderText = "id";
        //dataGridView1.Columns[0].DataPropertyName = "id";

        //dataGridView1.Columns[1].Name = "Kode";
        //dataGridView1.Columns[1].HeaderText = "Kode";
        //dataGridView1.Columns[1].DataPropertyName = "kosat";

        //dataGridView1.Columns[2].HeaderText = "Keterangan";
        //dataGridView1.Columns[2].Name = "Keterangan";
        //dataGridView1.Columns[2].DataPropertyName = "keterangan";

        //dataGridView1.Columns[1].SortMode = DataGridViewColumnSortMode.Automatic;
        //dataGridView1.Columns[2].SortMode = DataGridViewColumnSortMode.Automatic;

        //adapterKodeSatuan.Fill(dataTableKodeSatuan);
        //dataViewKodeSatuan = dataTableKodeSatuan.DefaultView;
        //dataGridView1.DataSource = dataViewKodeSatuan;
        ////dataGridView1.Columns[0].Visible = false;
        //Console.WriteLine("dataGridView1.Rows.Count = " + dataGridView1.Rows.Count);
        //dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true;

        //this.dataGridView1.Columns[0].Visible = false;


        //try
        //{
        //    Connection.Connector(server, database, user, password);
        //    listView1.Columns.Add("Kode", 70);
        //    listView1.Columns.Add("Keterangan", 140);
        //    //listView1.Items.Clear();
        //    adapterKodeSatuan = new SqlDataAdapter("SELECT * FROM KOSAT WHERE DELETEFLAG='N' ", Connection.sqlConnection);
        //    DataTable dt = new DataTable();
        //    adapterKodeSatuan.Fill(dt);
        //    ListViewItem listitem;
        //    Console.WriteLine("size = " + dt.Rows.Count);
        //    for (int i = 0; i < dt.Rows.Count; i++)
        //    {
        //        DataRow dr = dt.Rows[i];

        //        listitem = new ListViewItem();
        //        listitem.SubItems.Add( dr[0].ToString() );
        //        listitem.SubItems.Add( dr[1].ToString() );
        //        listitem.SubItems.Add( dr[2].ToString() );
        //        Console.WriteLine("aaa = " + dr[0].ToString());
        //        Console.WriteLine("bbb = " + dr[1].ToString());
        //        Console.WriteLine("ccc = " + dr[2].ToString());
        //        listView1.Items.Add(listitem);

        //    }

        //    listView1.Show();
        //}
        //catch (Exception ms) 
        //{
        //    Console.WriteLine("aaa");
        //}
    }        

    private void toolStripButton2_Click(object sender, EventArgs e)
    {
        toolStripButton1.Enabled = false;
        toolStripButton2.Enabled = false;
        toolStripButton3.Enabled = false;

        toolStripButton4.Visible = false;
        toolStripButton5.Visible = false;
        toolStripButton6.Visible = false;
        toolStripButton7.Visible = false;

        toolStripButton10.Visible = true;
        toolStripButton11.Visible = true;

        kodesatuanTxt.Enabled   = true;
        keteranganTxt.Enabled   = true;
        deleteFlag.Enabled      = true;
    }

    private void kodeSatuan_Load(object sender, EventArgs e)
    {
        kodesatuanTxt.Enabled   = false;
        keteranganTxt.Enabled   = false;
        deleteFlag.Enabled      = false;

        toolStripButton2.Visible = false;
        toolStripButton3.Visible = false;
        toolStripButton10.Visible = false;
        toolStripButton11.Visible = false;

        //kodeSatuanList();//this is my function that i call to datagridview or list

    }

    private void toolStripButton11_Click(object sender, EventArgs e)
    {
        DialogResult batal = MessageBox.Show("Perubahan dibatalkan ?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (batal == DialogResult.Yes)
        {
            //this.Close();
            kodesatuanTxt.Text = kosat;
            keteranganTxt.Text = ket;
            kodesatuanTxt.Enabled   = false;
            keteranganTxt.Enabled   = false;
            deleteFlag.Enabled      = false;

            toolStripButton1.Enabled = true;
            toolStripButton2.Enabled = true;
            toolStripButton3.Enabled = true;

            toolStripButton4.Visible = true;
            toolStripButton5.Visible = true;
            toolStripButton6.Visible = true;
            toolStripButton7.Visible = true;
            toolStripButton8.Visible = true;
            toolStripButton9.Visible = true;

            toolStripButton10.Visible = false;
            toolStripButton11.Visible = false;
        }

    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void toolStripButton1_Click(object sender, EventArgs e)
    {
        kodesatuanTxt.Enabled       = true;
        keteranganTxt.Enabled       = true;
        deleteFlag.Enabled          = true;
        toolStripButton10.Visible   = true;
        toolStripButton11.Visible   = true;
        toolStripButton1.Enabled    = false;
        toolStripButton2.Visible    = false;
        toolStripButton3.Visible    = false;
        toolStripButton4.Enabled    = false;
        toolStripButton5.Enabled    = false;
        toolStripButton6.Enabled    = false;
        toolStripButton7.Enabled    = false;
        toolStripButton8.Enabled    = false;
        toolStripButton9.Enabled    = false;

        kodesatuanTxt.Text = null;
        keteranganTxt.Text = null;

        idLbl.Text = "null";

    }

    private void toolStripButton10_Click(object sender, EventArgs e)
    {//ini setelah saya menekan tombol save...atau simpan
        try
        {
            string nonAktif = "N";
            string keteranganTmp = null;
            if (kodesatuanTxt.Text.Equals(""))
            {
                MessageBox.Show("Kode satuan tidak boleh kosong!", "Kode Satuan");
                kodesatuanTxt.Focus();
                return;
            }               
            else
            {
                if(deleteFlag.Checked == true){
                    nonAktif = "Y";
                }
                if(!keteranganTxt.Text.Equals("")){
                    keteranganTmp = keteranganTxt.Text;
                }

                if (idLbl.Text.Equals("null"))
                {
                    Connection.Connector(server, database, user, password);
                    Connection.sqlCommand = new SqlCommand("SELECT * FROM kosat where kosat = '" + kodesatuanTxt.Text + "'", Connection.sqlConnection);
                    reader = Connection.sqlCommand.ExecuteReader();
                    if (reader.Read())
                    {
                        //String id = Convert.ToString(reader["id"]);
                        //jika data yang mau saya buat itu belum ada...baru bisa insert baru..
                        DialogResult avaiable = MessageBox.Show("Kode satuan " + kodesatuanTxt.Text + " sudah ada", "Duplicate", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        if (avaiable == DialogResult.Yes)
                        {
                            this.Close();
                        }
                        return;
                    }
                    else
                    {//ini coding buat insertnya..
                        Connection.sqlConnection.Close();
                        Connection.Connector(server, database, user, password);
                        Connection.sqlCommand = new SqlCommand();
                        Connection.sqlCommand.Connection = Connection.sqlConnection;
                        Connection.sqlCommand.CommandType = CommandType.Text;
                        Connection.sqlCommand.CommandText = "insert into kosat(kosat,keterangan,deleteFlag) values('" + kodesatuanTxt.Text + "','" + keteranganTmp + "','" + nonAktif + "')";
                        //con.Open();
                        Connection.sqlCommand.ExecuteNonQuery();
                        Connection.sqlConnection.Close();
                        kodeSatuanList();//disini saya panggil fungsi tadi..
                        //dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true;
                        //reader = Connection.sqlCommand.ExecuteReader();
                    }
                }
                else
                {
                    Connection.Connector(server, database, user, password);
                    Connection.sqlCommand = new SqlCommand();
                    Connection.sqlCommand.Connection = Connection.sqlConnection;
                    Connection.sqlCommand.CommandType = CommandType.Text;
                    Connection.sqlCommand.CommandText = "UPDATE kosat SET kosat = '" + kodesatuanTxt.Text + "', keterangan = '" + keteranganTmp + "', deleteFlag = '" + nonAktif + "' WHERE id = "+ idLbl.Text;
                    //con.Open();
                    Console.WriteLine(Connection.sqlCommand.CommandText);
                    Connection.sqlCommand.ExecuteNonQuery();
                    Connection.sqlConnection.Close();
                    kodeSatuanList();
                }

            }
        }
        catch
        {

        }
    }

    private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        System.Text.StringBuilder cellInformation = new System.Text.StringBuilder();
        cellInformation.AppendFormat("{0} = {1}", "ColumnIndex", e.ColumnIndex);
        cellInformation.AppendLine();
        cellInformation.AppendFormat("{0} = {1}", "RowIndex", e.RowIndex);
        cellInformation.AppendLine();
        string row = dataGridView1.Rows[e.RowIndex].ToString();
        MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString(), "aa");//berdasarkan coding, kalau di coding 3 row, 1 row hidden brrt jadinya tetap 3 row
        MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString(), "CellMouseClick Event");//berdasarkan tampilan, kalau di coding 3 row, 1 row hidden jadinya sisa 2 row
        //kodesatuanTxt.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
        //keteranganTxt.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
        ////kodesatuan         = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
        ////keterangan         = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
        //toolStripButton2.Visible = true;
        //toolStripButton3.Visible = true;           

    }

    private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        dataGridView1.Columns[1].SortMode = DataGridViewColumnSortMode.Automatic;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        dataGridView1.Columns[1].SortMode = DataGridViewColumnSortMode.Automatic;
    }

    private void dataGridView1_SelectionChanged(object sender, EventArgs e)
    {
        if (dataGridView1.SelectedCells.Count > 0)
        {
            int selectedrowindex        = dataGridView1.SelectedCells[0].RowIndex;
            DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
            string x = Convert.ToString(selectedRow.Cells[0].Value);
            string code          = Convert.ToString(selectedRow.Cells[1].Value);
            string description   = Convert.ToString(selectedRow.Cells[2].Value);
            //string a = Convert.ToString(selectedRow.Cells["ID"].Value); //ID nama dari  header table
            Console.WriteLine("a = "+x);
            Console.WriteLine("kodee = " + code);
            Console.WriteLine("ket = " + description);

            idLbl.Text            = x; 
            kodesatuanTxt.Text = code;
            keteranganTxt.Text = description;
            kosat = code;
            ket = description;
            toolStripButton2.Visible = true;
            toolStripButton3.Visible = true; 

        }
    }
}

2 个答案:

答案 0 :(得分:0)

在Form_load事件中编写以下代码行:

dataGridView1.Columns[0].Visible = false;

在自定义方法中删除该行。

或者您可以将句子移到最后一个方法:

private void kodeSatuanList()//this one
{
    Connection.sqlConnection.Close();
            Connection.Connector(server, database, user, password);


    adapterKodeSatuan = new SqlDataAdapter("SELECT ID,KOSAT,KETERANGAN FROM KOSAT", Connection.sqlConnection);
    dataTableKodeSatuan.Clear();
    dataGridView1.ClearSelection();
    adapterKodeSatuan.Fill(dataTableKodeSatuan);
    dataViewKodeSatuan = dataTableKodeSatuan.DefaultView;

    dataGridView1.ColumnCount = 3;

    dataGridView1.Columns[0].Name = "id";
    dataGridView1.Columns[0].HeaderText = "id";
    dataGridView1.Columns[0].DataPropertyName = "id";

    dataGridView1.Columns[1].Name = "Kode";
    dataGridView1.Columns[1].HeaderText = "Kode";
    dataGridView1.Columns[1].DataPropertyName = "kosat";

    dataGridView1.Columns[2].HeaderText = "Keterangan";
    dataGridView1.Columns[2].Name = "Keterangan";
    dataGridView1.Columns[2].DataPropertyName = "keterangan";

    dataGridView1.Columns[1].SortMode = DataGridViewColumnSortMode.Automatic;
    dataGridView1.Columns[2].SortMode = DataGridViewColumnSortMode.Automatic;

    dataGridView1.DataSource = dataViewKodeSatuan;
    Console.WriteLine("dataGridView1.Rows.Count = " + dataGridView1.Rows.Count);
    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Selected = true;

    dataGridView1.Columns[0].Visible = false; //this..column id, i set it false..
}   

答案 1 :(得分:0)

在某些情况下,我确认填充.Visible时可能会丢失第一列DataGridView属性。

我解决了在最后一个位置移动此列或将DataColumn.ColumnMapping设置为MappingType.Hidden

在您的代码中尝试将adapterKodeSatuan的初始化更改为:

adapterKodeSatuan = new SqlDataAdapter("SELECT KOSAT, KETERANGAN, ID FROM KOSAT", Connection.sqlConnection);

因此,您可以修改.Visible列的ID属性,将其作为dataGridView1.Columns[2]访问。

仅当列无用且您在代码的其他部分不需要时才使用DataColumn.ColumnMapping解决方案。