Я новичок в Stackoverflow.C# program Если утверждения выдаются
На мою работу мне была назначена задача создать скрипт/программу, которая будет регистрировать людей и сотрудников, которые посещают каждую из 15 + школ, находящихся в моем районе, в базу данных доступа, чтобы административные люди могли ее просмотреть , Я решил использовать C#, чтобы эта программа произошла.
Проблема, с которой я столкнулся с моим кодом, заключается в том, что при загрузке формы он будет проходить через ряд операторов IF, которые определяют, в какой школе они находятся, на основе двух символов имени компьютера, прежде чем он предложит пользователям ввести их имени и причине посещения школы.
Когда я отлаживаю свой код, я ввожу свое имя и причину, затем я нажимаю кнопку «Сохранить», которая будет вводить в базу данных доступа информацию, такую как имя человека, причины посещения человека, временную метку и какую школу они находятся. Но когда я нажимаю save и смотрю на процесс выполнения посредством отладки, он сохраняет только имя и причину, но не временную метку и школу. Только так, я могу получить его, чтобы сохранить временную метку и школу, если я попытаюсь изменить эти строковые значения (не позволяю мне редактировать, что хорошо), что я не должен делать.
Вот мой код ниже для той формы, которую пользователь вводит данные:
namespace district_logprogram
{
public partial class district_CheckIn : Form
{
public district_CheckIn()
{
InitializeComponent();
txtTime.Text = DateTime.Now.ToString();
txtLocation.Text = ToString();
}
private void txtTime_TextChanged(object sender, EventArgs e)
{
//displays date and time on txtTime text box in Check In menu.
//On pressing 'Save' it will input date/time into checkIn column in district_checkIn table
var today = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss");
txtTime.Text = today;
}
private void txtLocation_TextChanged(object sender, EventArgs e)
{
//displays which school you are located in
//On pressing 'Save' it will input the school into location column in district_checkIn table
System.Threading.Thread.Sleep(5);
if (System.Environment.MachineName.Contains("01"))
{
txtLocation.Text = "School 1";
}
else if (System.Environment.MachineName.Contains("02"))
{
txtLocation.Text = "School 02";
}
else if (System.Environment.MachineName.Contains("03"))
{
txtLocation.Text = "School 03";
}
else if (System.Environment.MachineName.Contains("04"))
{
txtLocation.Text = "School 04";
}
else if (System.Environment.MachineName.Contains("05"))
{
txtLocation.Text = "School 05";
}
else if (SystS6.Environment.MachineName.Contains("06"))
{
txtLocation.Text = "School 06";
}
else if (System.Environment.MachineName.Contains("07"))
{
txtLocation.Text = "School 07";
}
else if (System.Environment.MachineName.Contains("08"))
{
txtLocation.Text = "School 08";
}
else if (System.Environment.MachineName.Contains("09"))
{
txtLocation.Text = "School 09";
}
else if (System.Environment.MachineName.Contains("10"))
{
txtLocation.Text = "School 10";
}
else if (System.Environment.MachineName.Contains("11"))
{
txtLocation.Text = "School 11";
}
else if (System.Environment.MachineName.Contains("12"))
{
txtLocation.Text = "School 12";
}
else if (System.Environment.MachineName.Contains("13"))
{
txtLocation.Text = "School 13";
}
else if (System.Environment.MachineName.Contains("14"))
{
txtLocation.Text = "School 14";
}
else if (System.Environment.MachineName.Contains("15"))
{
txtLocation.Text = "School 15";
}
else if (System.Environment.MachineName.Contains("16"))
{
txtLocation.Text = "School 16";
}
else if (System.Environment.MachineName.Contains("17"))
{
txtLocation.Text = "School 17";
}
else if (System.Environment.MachineName.Contains("18"))
{
txtLocation.Text = "School 18";
}
else if (System.Environment.MachineName.Contains("19"))
{
txtLocation.Text = "School 19";
}
else if (System.Environment.MachineName.Contains("20"))
{
txtLocation.Text = "School 20";
}
else if (System.Environment.MachineName.Contains("21"))
{
txtLocation.Text = "School 21";
}
else if (System.Environment.MachineName.Contains("22"))
{
txtLocation.Text = "School 22";
}
else if (System.Environment.MachineName.Contains("23"))
{
txtLocation.Text = "School 23";
}
else
{
//If computer hostname is not configured correctly, it will display message below
btnSave.Enabled = false;
txtLocation.Text = "Cannot determine school name! Check hostname!";
}
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
districtcheckinBindingSource.EndEdit();
district_checkinTableAdapter.Update(this.districtDB.district_checkin);
Close(); //this closes the check in menu
MessageBox.Show("You are checked in!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "An error occurred during check in!", MessageBoxButtons.OK, MessageBoxIcon.Error);
districtcheckinBindingSource.ResetBindings(false);
}
}
private void district_CheckIn_Load(object sender, EventArgs e)
{
this.district_checkinTableAdapter.Fill(this.districtDB.district_checkin); //opens connection to district_checkin table
districtcheckinBindingSource.DataSource = this.districtDB.district_checkin; //opens connection to district_checkin table
txtName.Focus(); //focuses cursor on txtName text box field
this.districtDB.district_checkin.Adddistrict_checkinRow(this.districtDB.district_checkin.Newdistrict_checkinRow()); //begins a new row for adding records
districtcheckinBindingSource.MoveLast(); //moves new record to end of table - "shifts it down"
}
}
}
Вот как это выглядит, когда я его отладки после ввода информации: only the name and reason are inputted but not time and school name А вот что он должен выглядеть например, после ввода информации: Любые предложения по решению этой проблемы очень помогли бы! :)
Создайте цикл для замены 23 (!) Идентичных кодовых заглушек на один. – Gustav
Я сделал это в своем коде, и теперь он работает немного быстрее. спасибо за предложение! – mrdrumboy21
Это не может быть много. Это скорее вопрос обслуживания и удобочитаемости. – Gustav