我已将程序连接到访问数据库文件,当我选择组合框中的数字(1,2,3等)时,我想自动填写表单中的其他文本框..如果它是一个string ..例如,如果我在组合框中选择一个字符串(例如名称),它会自动填充其他文本框,但如果它是一个整数则不起作用。
我知道我必须转换为int,但我不知道如何因为我有一个查询:
private void iD_FurnizorComboBox_SelectedIndexChanged_1(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query;
query = "select * from Furnizori where id_furnizor = '" + iD_FurnizorComboBox.Text + "'";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
numeTextBox.Text = reader["nume"].ToString();
adresaTextBox.Text = reader["adresa"].ToString();
localitateTextBox.Text = reader["localitate"].ToString();
judetTextBox.Text = reader["judet"].ToString();
}
connection.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.Close();
}
}
我不知道在哪里解析字符串到int ..谢谢!!
答案 0 :(得分:0)
使用int.TryParse
将字符串解析为int。你也有一些问题,如sql注入,而不是使用using
- 语句。
private void iD_FurnizorComboBox_SelectedIndexChanged_1(object sender, EventArgs e)
{
int id_furnizor;
if(!int.TryParse(iD_FurnizorComboBox.Text, out id_furnizor))
{
MessageBox.Show("id_furnizor is not a valid integer: " + iD_FurnizorComboBox.Text);
return;
}
using(var connection=new OleDbConnection("Connection String"))
{
try
{
string query = @"select f.*
from Furnizori f
where id_furnizor = @id_furnizor;";
OleDbCommand command = new OleDbCommand(query, connection);
command.Parameters.Add("@id_furnizor", OleDbType.Integer).Value = id_furnizor;
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
if (reader.Read())
{
numeTextBox.Text = reader.GetString(reader.GetOrdinal("nume"));
adresaTextBox.Text = reader.GetString(reader.GetOrdinal("adresa"));
localitateTextBox.Text = reader.GetString(reader.GetOrdinal("localitate"));
judetTextBox.Text = reader.GetString(reader.GetOrdinal("judet"));
}
} catch (Exception ex)
{
throw; // redundant but better than throw ex since it keeps the stacktrace
}
}// not necessary to close connection, done implicitly
}