やろうとしていること
Form1のボタンを押すとForm2(書き込みフォーム)が開く、
データを入力し、ボタンを押すとクエリが実行される
Form1のDataGridViewに反映される
Form1
c#
1public partial class Form1 : Form 2 { 3 // 接続文字列クラス 4 Server server = new Server(); 5 // 接続保持用フィールド 6 NpgsqlConnection connsql = new NpgsqlConnection(); 7 // データテーブル 8 public static DataTable dt= new DataTable(); 9 10 public Form1() 11 { 12 InitializeComponent(); 13 } 14 15 private void Form1_Load(object sender, EventArgs e) 16 { 17 // サーバー接続 18 try 19 { 20 // PostgreSQLへ接続 21 connsql = new NpgsqlConnection(server.conn_str); 22 connsql.Open(); 23 } 24 catch (Exception ex) 25 { 26 // エラー 27 MessageBox.Show(ex.Message, "エラー", MessageBoxButtons.OK, 28 MessageBoxIcon.Error); 29 30 return; 31 } 32 // クエリ実行 33 ExecutionQuery("SELECT * FROM article", dt); 34 35 // 結果を表示 36 dataGridView1.DataSource = dt; 37 }
クエリ実行メソッド(Form1)
c#
1public void ExecutionQuery(string DB, DataTable table) 2 { 3 try 4 { 5 using (var sdr = connsql.CreateCommand()) 6 { 7 sdr.CommandText = DB; 8 var sda = new NpgsqlDataAdapter(sdr); 9 sda.Fill(table); 10 } 11 } 12 catch (Exception ex) 13 { 14 // エラー 15 MessageBox.Show(ex.Message, "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); 16 17 return; 18 } 19 }
Form2
c#
1 private void button1_Click(object sender, EventArgs e) 2 { 3 var date = DateTime.Now; 4 int id_a= (int)Form1.dataGridView1.CurrentRow.Cells[0].Value; 5 6 // 書き込み 7 string sql = $@" 8 INSERT 9 INTO 10 rental 11 (id_a, 12 id_s, 13 update_date, 14 place, 15 status) 16 VALUES( 17 '{id_a}', 18 '{textBoxID.Text}', 19 '{date}', 20 '{comboBoxPlace.Text}', 21 '{comboBoxStatus.Text}') 22 "; 23 24 // クエリ実行 25 Form1.ExecutionQuery(sql, Form1.dt); 26 // 結果を表示 27 Form1.dataGridView1.DataSource = Form1.dt; 28 }
Form2エラー:
CS0120 静的でないフィールド、メソッド、またはプロパティ 'Form1.dataGridView1' で、オブジェクト参照が必要です
CS0120 静的でないフィールド、メソッド、またはプロパティ 'Form1.ExecutionQuery(string, DataTable)' で、オブジェクト参照が必要です
重大度レベル コード 説明 プロジェクト ファイル 行 抑制状態
CS0120 静的でないフィールド、メソッド、またはプロパティ 'Form1.dataGridView1' で、オブジェクト参照が必要です
解決方法としてform1のインスタンスをform2に渡すというのを見つけたのですがどうすればいいのかわかりません。
またForm2からForm1のクエリ実行メソッドを実行することは不可なのでしょうか??
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/04/25 05:40
退会済みユーザー
2019/04/25 05:51
2019/04/25 06:03
退会済みユーザー
2019/04/25 06:14
2019/04/25 06:17
退会済みユーザー
2019/04/25 06:26 編集
2019/04/25 06:34
退会済みユーザー
2019/04/25 06:44
2019/04/25 06:57
退会済みユーザー
2019/04/25 08:05