トップ回答者
Form1_Loadイベントでデータを表示するには?

質問
-
VC# 2010 Proで下記のコードでForm1のロード時にPostgreSQLのレコードを表示させようと思いますがデバッグは正常にとおるものの、やり方が間違っているのか表示してくれません。
そもそもLoadイベントでやろうとしているのが間違っているのか?どのようにするべきなのか、教えてください。お願いいたします。
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using Npgsql;using Mono;using System.Data.SqlClient;
namespace PostgreSQLTEst{public partial class Form1 : Form{private DataSet ds = new DataSet();private DataTable dt = new DataTable();
public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){try{
NpgsqlConnection conn = new NpgsqlConnection("Server=192.168.0.30;Port=5432;User Id=user;Password=pass;Database=db;Encoding=UNICODE");
conn.Open();
NpgsqlDataAdapter das = new NpgsqlDataAdapter();
das.SelectCommand = new NpgsqlCommand("SELECT * FROM users ORDER BY id", conn);
ds.Reset();
das.Fill(ds);
dt = ds.Tables[0];
BindingSource bindingSource1 = new BindingSource();bindingSource1.DataSource = dt;bindingNavigator1.BindingSource = bindingSource1;dataGridView1.DataSource = bindingSource1;dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
conn.Close();}catch (Exception msg){// something went wrong, and you wanna know whyMessageBox.Show(msg.ToString());throw;}}
}}}
回答
すべての返信
-
-
かなりレスが付いてますが・・・
> そもそもLoadイベントでやろうとしているのが間違っているのか?
これはデータの表示的には全く問題ないですね。もちろん佐祐理さんの指摘されている問題はありますが。
あとmars12さんの指摘されておられるように、余分な処理が入っているようなので、以下のようにコードを縮めることが可能です。あとコネクションの接続を閉じるのは finally ブロックで行うべきだと思います。
NpgsqlConnection conn = new NpgsqlConnection ("Server=192.168.0.30;Port=5432;User Id=user;Password=pass;Database=db;Encoding=UNICODE"); try { conn.Open(); NpgsqlCommand command = new NpgsqlCommand("SELECT * FROM users ORDER BY id", conn); NpgsqlDataAdapter das = new NpgsqlDataAdapter(command); DataTable dt = new DataTable(); das.Fill(dt); dataGridView1.DataSource = dt; } catch (Exception ex) { MessageBox.Show(ex.ToString()); throw; } finally { conn.Close(); }
ひらぽん http://d.hatena.ne.jp/hilapon/ -
ひらぽんさん、こんにちは、Loadイベントでのデータ表示の件については、問題もふくめて理解しました。
> あとmars12さんの指摘されておられるように、余分な処理が入っているようなので、以下のようにコードを縮めることが可能です。とありますが、掲示していただいたコードではbindingNavigatorの処理部分を抜いていますがこれ↓は、別なイベントに書いて処理すべきということなのでしょうか?
BindingSource bindingSource1 = new BindingSource();bindingSource1.DataSource = dt;bindingNavigator1.BindingSource = bindingSource1;
ちょっと、今、実行環境が手元に無いのですが(自宅に帰らないと...)気になったもので脱線かもしれませんが質問させていただきました。
- 回答の候補に設定 ひらぽんModerator 2010年7月14日 6:38
-
すみません。回答の候補、押し間違えました。<(_ _;)>
#なんか表示がおかしい・・・
> 掲示していただいたコードではbindingNavigatorの処理部分を抜いていますが
> これ↓は、別なイベントに書いて処理すべきということなのでしょうか?> BindingSource bindingSource1 = new BindingSource();> bindingSource1.DataSource = dt;> bindingNavigator1.BindingSource = bindingSource1;
なぜか見落としてました。ケアレスミスです。忘れて下さい・・・<(_ _;)>
ひらぽん http://d.hatena.ne.jp/hilapon/