I am writing a kind of democrazy Programm for my collegues with a SQL Server (Express).
Thusfar i got along with it pretty well, but I fail for about an hour not, to create a simple way of using a SqlCommand with parameters, that can be null, but don't always are.
My current "solution" looks like this:
public bool CreateSubTopic(string subtopic, DateTime enddate, int maxParts, int BitKeepEntries)
{
Connected = true;
var myDict = GetSubtopics(HelpClass.TopicId);
if (myDict.ContainsKey(subtopic))
{
return false;
}
myCommand = null;
myCommand = new SqlCommand("insert into SubtopicsParameters(FK_Topic, Subtopic, StartDate, Enddate, MaxParticipants, KeepsEntries) values(" +
HelpClass.TopicId + "," +
subtopic + "," +
DateTime.Today + "," +
enddate + "," +
maxParts + "," +
BitKeepEntries + ")");
myCommand.ExecuteNonQuery();
Connected = false;
return true;
}
The Table i write in has the additional primary Key PK_ID
. The columns FK_Topic
, Enddate
and MaxParticipants
can be null, based on checkboxes on a form.
The Problem is, I could just write 7 different methodes, but it would be dirty.
Do you have a solution ?
€: The Solution I use now looks like this:
public bool CreateSubTopic(string subtopic, DateTime enddate, int maxParts, bool KeepEntries)
{
var myDict = GetSubtopics(HelpClass.TopicId);
if (myDict.ContainsKey(subtopic))
{
return false;
}
Connected = true;
myCommand = null;
myCommand = new SqlCommand("insert into SubtopicsParameters(FK_Topic, Subtopic, StartDate, Enddate, MaxParticipants, KeepsEntries) values(" +
"@FKParam," + " @SubtopicParam," + "@Startdateparam," + "@Enddateparam," + "@MaxPartsParam," + "@KeepEntriesParam)", myConnection);
myCommand.Parameters.AddWithValue("FkParam", HelpClass.TopicId);
myCommand.Parameters.AddWithValue("SubtopicParam", subtopic);
myCommand.Parameters.AddWithValue("@Startdateparam", DateTime.Today);
if (enddate != DateTime.Today)
{
myCommand.Parameters.AddWithValue("@Enddateparam", enddate);
}
else
{
myCommand.Parameters.AddWithValue("@Enddateparam", DBNull.Value);
}
if (maxParts == 0)
{
myCommand.Parameters.AddWithValue("@MaxPartsParam", DBNull.Value);
}
else
{
myCommand.Parameters.AddWithValue("@MaxPartsParam", maxParts);
}
if(KeepEntries == true)
{
myCommand.Parameters.AddWithValue("@KeepEntriesParam", 1);
}
else
{
myCommand.Parameters.AddWithValue("@KeepEntriesParam", 0);
}
myCommand.ExecuteNonQuery();
Connected = false;
return true;
}
This works, is safe and based on your comments and answers :) Thank you.