我正在使用在 Access 中创建的本地数据库,我将其作为数据源添加到我的 C# 项目中。我有 2 种形式:RoomSelect
和RoomActiveSession
.
RoomSelect 包含一个带有 4 个值(房间号)和一个按钮的列表框。用户选择房间号,单击“确定”,然后应重定向到RoomActiveSession
表单,其中给定房间号的活动会话应显示在 DGV 中。
RoomActiveSession 包含用于显示结果的 dataGridView。
我的问题是:如何正确访问 DGVRoomSelect
以显示我的查询结果?
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
根据this post datagird access from another form我应该为DGV创建get,set属性RoomActiveSession
,但我不知道该怎么做(我应该在RoomActiveSession
设计器中修改代码吗?)