我在Access中創建一個本地數據庫,我添加一個數據源到我的C#項目工作的dataGridView。我有兩種形式:RoomSelect
和RoomActiveSession
。顯示查詢結果的另一種形式
RoomSelect包含具有4個值(房間號)和一個按鈕列表框的。用戶選擇房間號碼,單擊確定,並且應該被重定向到RoomActiveSession
表格,其中給定房間號碼的活動會話應該在DGV中顯示。
RoomActiveSession包含的dataGridView的顯示結果。
我的問題是:如何才能正確地我從RoomSelect
訪問DGV顯示我的查詢的結果呢?
RoomSelect
代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AutoReg
{
public partial class RoomSelect : Form
{
DataTable queryResult = new DataTable();
public string RoomID;
RoomActiveSession RoomActiveSessionForm = new RoomActiveSession();
public RoomSelect()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
switch (listBox1.SelectedItem.ToString())
{
case "MB0302":
RoomID = listBox1.SelectedItem.ToString();
RoomActiveSessionForm.ShowDialog();
roomQuery();
break;
case "MC1001":
RoomID = listBox1.SelectedItem.ToString();
RoomActiveSessionForm.ShowDialog();
roomQuery();
break;
case "MC3203":
RoomID = listBox1.SelectedItem.ToString();
RoomActiveSessionForm.ShowDialog();
roomQuery();
break;
case "MC3204":
RoomID = listBox1.SelectedItem.ToString();
RoomActiveSessionForm.ShowDialog();
roomQuery();
break;
}
}
public void roomQuery()
{
string ConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Kacper\\Desktop\\AutoReg\\AutoReg\\AutoReg.accdb;";
OleDbConnection MyConn = new OleDbConnection(ConnStr);
MyConn.Open();
//SQL query that todays sessions for the given roomID
string query = @"SELECT SessionID, SemesterA, SemesterB, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = @RoomID " +
" AND SessionDate = Date() ";
OleDbCommand command = new OleDbCommand(query, MyConn);
command.Parameters.Add("RoomID", OleDbType.Char).Value = RoomID;
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(queryResult);
if (queryResult.Rows.Count == 0)
{
MessageBox.Show("No active sessions today for the given room number");
MyConn.Close();
}
else
{
RoomActiveSession.dataGridView1.DataSource = queryResult;
MyConn.Close();
}
}
}
}
我就行收到一個錯誤:RoomActiveSession.dataGridView1.DataSource = queryResult;
'AutoReg.RoomActiveSession.dataGridView1' is inaccessible due to its protection level C:\Users\Kacper\Desktop\AutoReg\AutoReg\RoomSelect.cs
根據這個帖子datagird access from another form我應該創建得到,爲DGV在RoomActiveSession
設置屬性,但我也不太清楚如何做到這一點(我應該在RoomActiveSession
設計師修改代碼嗎?)
感謝您的廣泛的答案! – jaspernorth