概要
cscの作法、調べてみた。
練習問題やってみた。
練習問題
datagridにcsvを読み込め。
写真
サンプルコード
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.OleDb;
using System.Data;
using System.IO;
using System.Text;
using System.Collections.Generic;
class form1: Form {
DataGridView gd0;
form1() {
Text = "DataGrid";
ClientSize = new Size(580, 400);
gd0 = new DataGridView();
gd0.Location = new Point(50, 20);
gd0.Width = 500;
gd0.Height = 300;
Controls.AddRange(new Control[] {
gd0
});
Button btn1 = new Button();
btn1.Location = new Point(50, 330);
btn1.Text = "test";
btn1.Click += btn1_Click;
Controls.AddRange(new Control[] {
btn1
});
}
void btn1_Click(object sender, System.EventArgs e) {
Encoding enc = Encoding.GetEncoding("Shift_JIS");
string file = "test1.csv";
StreamReader reader = new StreamReader(file, enc);
string temp = reader.ReadToEnd();
string[] lines = temp.Split(new string[] {
"\r\n"
}, StringSplitOptions.None);
string[] spLine;
spLine = lines[0].Split(new char[] {
',',
'\t'
}, StringSplitOptions.None);
gd0.ColumnCount = spLine.Length;
for (int i = 0; i < spLine.Length; i++)
{
gd0.Columns[i].HeaderText = spLine[i].Trim('"');
}
DataGridViewRow[] rows = new DataGridViewRow[lines.Length - 1];
for (int i = 1; i < lines.Length; i++)
{
spLine = lines[i].Split(new char[] {
',' ,
'\t'
}, StringSplitOptions.None);
for (int j = 0; j < spLine.Length; j++)
{
spLine[j] = spLine[j].Trim('"');
}
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(gd0);
row.SetValues(spLine);
rows[i - 1] = row;
}
gd0.Rows.AddRange(rows);
MessageBox.Show("ok");
}
[STAThread]
public static void Main() {
Application.Run(new form1());
}
}
以上。