我不知道我的代码有什么问题,我真的需要这个项目的帮助。当我运行它时,它会搜索数据库,但只显示空行字段。此外,我有一个函数在表单启动时将数据加载到DGV LoadData()
。
private void bx_Search_TextChanged(object sender, EventArgs e)
{
string ss = bx_Search.Text;
SqlConnection con = new SqlConnection("Data Source=GH0ST;Initial Catalog=InventoryProjectDB;Integrated Security=True");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM PRODUCT WHERE PNAME LIKE '%" + ss + "%'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
LoadData
public void LoadData()
{
SqlConnection con = new SqlConnection("Data Source=GH0ST;Initial Catalog=InventoryProjectDB;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter(@"SELECT * FROM [dbo].[PRODUCT]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int ar = dataGridView1.Rows.Add();
dataGridView1.Rows[ar].Cells[0].Value = item["PID"].ToString();
dataGridView1.Rows[ar].Cells[1].Value = item["PName"].ToString();
dataGridView1.Rows[ar].Cells[2].Value = item["PPrice"].ToString();
if ((bool)item["PStatus"])
dataGridView1.Rows[ar].Cells[3].Value = "In Stock";
}
else
{
dataGridView1.Rows[ar].Cells[3].Value = "Out of Stock";
}
dataGridView1.Rows[ar].Cells[4].Value = item["PQTY"].ToString();
dataGridView1.Rows[ar].Cells[5].Value = item["PDateAdded"].ToString();
}
}
private void MAIN_Load(object sender, EventArgs e)
{
LoadData();
}
答案 0 :(得分:0)
我认为您可能缺少DataGridView.Refresh()来刷新布局。
private void bx_Search_TextChanged(object sender, EventArgs e)
{
string ss = bx_Search.Text;
SqlConnection con = new SqlConnection("Data Source=GH0ST;Initial Catalog=InventoryProjectDB;Integrated Security=True");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM PRODUCT WHERE PNAME LIKE '%" + ss + "%'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Refresh();
con.Close();
}