呐,我问个问题,关于combobox和textbox还有datagridview。

sky5940 2012-05-13 07:21:27

下面是代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace myobj
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private static SqlConnection conn;
DataTable t1 = new DataTable();
SqlDataAdapter da1 = new SqlDataAdapter();


private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//清空combobox2添加项
this.comboBox2.Items.Clear();

//清空combobox2中上次选择项
this.comboBox2.Text = "";

if (comboBox1.SelectedIndex == 0)
{
this.comboBox2.Items.Add("building");
this.comboBox2.Items.Add("post");
this.comboBox2.Items.Add("police");
this.comboBox2.Items.Add("office");
this.comboBox2.Items.Add("hospital");
}
else if (comboBox1.SelectedIndex == 1)
{

this.comboBox2.Items.Add("road");
this.comboBox2.Items.Add("railway");
}
else
{

this.comboBox2.Items.Add("river");
this.comboBox2.Items.Add("green");
}
}

private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{

}

private void textBox1_TextChanged(object sender, EventArgs e)
{
string i;
string s1 = "";
s1 = textBox1.Text;

if (textBox1.Text.Length == 0)
{
i = null;
//MessageBox.Show("请输入查询条件", "错误");
}
else
{
i = Convert.ToString(textBox1.Text);
//连接数据库
conn = new SqlConnection("server = (local); Database = fzmap; Integrated Security= true;MultipleActiveResultSets=true");

//打开连接
conn.Open();

//创建命令

SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;

cmd.CommandText = "select * from " + "'" + combobox2.Text + "' where name = " + "'" + textBox1.Text + "'";
//执行命令
DataSet dts = new DataSet();
SqlDataAdapter dat = new SqlDataAdapter(cmd);
dat.Fill(dts);
//将查询结果显示在DataGridView上
dataGridView1.DataSource = dts.Tables[0];

//关闭连接
conn.Close();
}
}
}


根据combobox2选择的内容选择sql里面的表,再在textbox1里输入名称,最后把有关内容显示在datagridview中。
代码有问题,但不知道错哪里
有没人帮忙看看代码,哪里有错?求指点啊
...全文
146 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Change_L 2012-05-14
  • 打赏
  • 举报
回复
表名不加单引号
熙风 2012-05-14
  • 打赏
  • 举报
回复
cmd.CommandText = "select * from " + combobox2.Text + " where name ='" + textBox1.Text + "'";
梦世界 2012-05-14
  • 打赏
  • 举报
回复
cmd.CommandText = "select * from " + "'" + combobox2.Text + "' where name = " + "'" + textBox1.Text + "'";


这语句这样写:“select * from "+combobox.text+" where name =‘“+textbox1.text+”’”
因为你拼的语句表加上单引号了
lilei_new 2012-05-14
  • 打赏
  • 举报
回复
还有你的图片也挂了.
lilei_new 2012-05-14
  • 打赏
  • 举报
回复
你的SQL语句有问题哦.因为"name"是关键字用于字段得加入"[]".
cmd.CommandText = "select * from " + "'" + combobox2.Text + "' where [name] = " + "'" + textBox1.Text + "'";

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧