在下面的代码中,我只想根据更改的选定组合框填充我的文本框。但我得到以下错误。
如果你帮助我,我会很感激。转换varchar值时转换失败 'System.Data.DataRowViewConvert.ToString()'到数据类型int。'
SqlConnection objConnection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\UniversityDataBase.mdf;Integrated Security=True");
private void comboBox1_Click(object sender, EventArgs e)
{
string query = "SELECT *FROM TutorTable";
SqlDataAdapter SDA = new SqlDataAdapter(query, objConnection);
DataTable dt = new DataTable();
SDA.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Tid";
objConnection.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sqlQuery = "SELECT *FROM TutorTable where Tid = '"+comboBox1.Text+ "Convert.ToString()'";
SqlCommand objCommand = new SqlCommand(sqlQuery, objConnection);
objConnection.Open();
objCommand.ExecuteNonQuery();
SqlDataReader dr;
dr = objCommand.ExecuteReader();
while (dr.Read())
{
string Tname = (string)dr["Tname"].ToString();
textBox1.Text = Tname;
}
}
答案 0 :(得分:2)
为什么在这段代码中使用Convert.ToString():
"SELECT * FROM TutorTable where Tid = '"+comboBox1.Text+ "Convert.ToString()'"
我认为正确的方法是:
"SELECT * FROM TutorTable where Tid = '"+comboBox1.Text+ "'"
但是考虑使用存储过程来阻止sql注入或使用ORM。
我认为comboBox1.Text
已经返回一个字符串值。所以,如果是这样,就没有必要放Convert.ToString(comboBox.Text)
,只需要把comboBox1.Text
根据文档,Text属性是一个字符串 https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.text(v=vs.110).aspx
答案 1 :(得分:0)
我发现解决方案如下:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\UniversityDataBase.mdf;Integrated Security=True");
string sqlQuery = "SELECT *FROM TutorTable WHERE Tid = '" + comboBox1.Text + "'";
SqlCommand objCommand = new SqlCommand(sqlQuery, con);
con.Open();
SqlDataReader dr;
dr = objCommand.ExecuteReader();
while (dr.Read())
{
string name = (string)dr["Tname"].ToString();
textBox1.Text = name;
}
}
答案 2 :(得分:0)
你已经得到了答案,但还有更多事情需要处理
您的代码
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sqlQuery = "SELECT *FROM TutorTable where Tid = '"+comboBox1.Text+ "Convert.ToString()'";
SqlCommand objCommand = new SqlCommand(sqlQuery, objConnection);
objConnection.Open();
objCommand.ExecuteNonQuery();
SqlDataReader dr;
dr = objCommand.ExecuteReader();
while (dr.Read())
{
string Tname = (string)dr["Tname"].ToString();
textBox1.Text = Tname;
}
}
需要注意的事项:
1)使用varabled而不是操纵sql
例如SELECT *FROM TutorTable where Tid = @id
并将id传递给sqlCommand对象
2)您无需在ExecuteNonQuery
SqlDataReader
3)您需要使用if(dr.Read()
)而不是while
4)您可以直接指定值文本框。
例如texBox1.Text = dr["Tname"].ToString();
5)关闭objConnection