LoginSignup
2
4

More than 5 years have passed since last update.

C# DataSetで作ったGridView TIPS

Last updated at Posted at 2015-07-13

基本

public partial class Form1 : Form
    {
        DataSet dataSet1 = new DataSet();
        DataTable dt = new DataTable();

        public Form1()
        {
            InitializeComponent();

            //ひとつしか選択できないようにする
            dataGridView1.MultiSelect = false;
            //列の幅を一杯に広げる
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        }


        private void Form1_Load(object sender, EventArgs e)

        {
            dt.Columns.Add("Name", typeof(string));
            dt.Columns.Add("Description", typeof(string));
            // 4行追加します。
            for (int i = 0; i < 4; i++)
            {
                DataRow row = dt.NewRow();
                row["Name"] = "名前";
                row["Description"] = "説明";
                dt.Rows.Add(row);
            }
            //GridViewにセット
            dataSet1.Tables.Add(dt);
            //テーブルデータ表示
            dataGridView1.DataSource = dt;
        }
 }

選択した下に空白行を追加

        private void Add_btn_Click(object sender, EventArgs e)
        {
                int insert_pos = 0;
                insert_pos = dataGridView1.CurrentRow.Index + 1;
                //挿入する行の生成
                DataRow newRow = dataSet1.Tables[0].NewRow();
                //選択行の下に追加
                dataSet1.Tables[0].Rows.InsertAt(newRow, insert_pos);
            }
        }

選択行を削除

        private void Delete_bt_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null)
            {
                MessageBox.Show("これ以上は削除出来ません");
            }
            else
            {
                DataRow myRow = dataSet1.Tables[0].Rows[dataGridView1.CurrentRow.Index];
                myRow.Delete();
            }

        }

選択セルに文字列追加

   if (dataGridView1.CurrentRow == null)
            {
                dt.Rows.Add("文字列");
            }
            else
            {
                dataGridView1.CurrentCell.Value = "文字列";
            }
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4