I gave +1 to this question because I was about to ask for the same, but I found the way to do it, yes, it is possible to do what he's asking.
This article about Arrays and Collections helped me, I used a Generic List to this example because I think it's easier to add items to a dynamic Collection while we are fetching records from database. I changed some of the code to match the question.
//create a class and paste this.
public class createsCollection
{
private static SqlConnection getConnection()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source=yourPCName\SQLEXPRESS;Initial Catalog=..";
return con;
}
public static List <DateTime?> datesList(string room)
{
using (var con = new SqlConnection(getConnection().ConnectionString))
{
SqlDataReader dReader;
List <DateTime?> dates = new List<DateTime?>();
var cad = "SELECT Date from yourTbl where room = @Rn";
using (var sqlCommand = new SqlCommand(cad, con))
{
try
{ sqlCommand.CommandType = CommandType.Text
sqlCommand.Parameters.AddWithValue("@Rn", room);
con.Open();
dReader = sqlCommand.ExecuteReader();
if (dReader.HasRows == true)
{
while (dReader.Read())
dates.Add(DateTime.Parse(dReader["Date"].ToString()));
}
return dates;
}
catch (Exception ex)
{ MessageBox.Show("Error: " + ex.Message);
return null;
}
}
}
}
}
In your Form:
List<DateTime?> datesLst = new List<DateTime?>();
List<DateTime> notNullableList = new List<DateTime>();
private void Form_Load(object sender, EventArgs e)
{
datesLst = createsCollection.datesList("103"); //this can be changed e.g Button.Text
//We need to convert the nullable DateTime List 'datesLst' to a non-nullable
//DateTime array in order to pass it to the BoldedDates Property.
if (datesLst != null) //if there were records from the db
{
foreach (DateTime? dtm in datesLst)
{
string str = dtm.GetValueOrDefault().ToShortDateString();
DateTime val;
if (DateTime.TryParse(str, out val))
{
notNullableList.Add(val); //add not-null value to the new generic list
}
}
monthCalendar1.BoldedDates = notNullableList.ToArray(); //bold the dates gathered from the db to the Month Calendar
monthCalendar1.Update();
monthCalendar1.UpdateBoldedDates();
}
}
It's a way to do it, and I believe there are better way to implement it but this works pretty good for me when I tested it.
If you want to use a fixed size Array instead of a List, you may want to do a first query that returns the number of (Date) rows based on the specified condition and set it to the array size, also is not necessary to return a nullable List but I did it as my preference. Cheers.