未获取预定义Datagrid列中的数据

本文关键字:数据 Datagrid 获取 预定义 | 更新日期: 2023-09-27 18:27:46

我有一个预定义的数据网格列,它在表单加载时加载。我想要的是,当我在文本框中输入产品的id或名称时,我希望它显示在数据网格列中。但当我输入Id或产品名称时,列中不会显示任何内容。我尝试了以下代码:

   public Form1()
    {
        InitializeComponent();
        load();
    }
    void load()
    {
        string cc = "";
        int n;
        if (int.TryParse(textBox1.Text, out n))
        {
            cc = "product_Id = " + textBox1.Text.Trim();
        }
        else
        {
            cc = "product_Name LIKE '%" + textBox1.Text.Trim() + "%'";
        }
        if (string.IsNullOrEmpty(textBox1.Text))
        {
            cc = "1 = 1";
        }
        SqlConnection con = new SqlConnection("Data Source=SUMIT;Initial Catalog=Project;Integrated Security=True");
        SqlCommand cmd = new SqlCommand("Select product_Name as [Product Name],cast(actual_Sp as INT) * '" + textBox2.Text + " 'as [Actual SP] from Product WHERE " + cc, con); ;
    cmd.CommandType = CommandType.Text;
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        dataGridView1.AutoGenerateColumns = false;
        dataGridView1.DataSource = null;
        dataGridView1.ColumnCount = 7;
        dataGridView1.Columns[0].Name = "ProductId";
        dataGridView1.Columns[0].HeaderText = "PID";
        dataGridView1.Columns[0].DataPropertyName = "product_Id";
        dataGridView1.Columns[1].HeaderText = "S.N.";
        dataGridView1.Columns[1].Name = "Serial Number";
        // dataGridView1.Columns[1].DataPropertyName = "ContactName";
        dataGridView1.Columns[2].Name = "Particulars";
        dataGridView1.Columns[2].HeaderText = "Particulars";
        dataGridView1.Columns[2].DataPropertyName = "product_Name";

        dataGridView1.Columns[3].Name = "Unit Quantity";
        dataGridView1.Columns[3].HeaderText = "Unit Quantity";
        //dataGridView1.Columns[3].DataPropertyName = "product_Name";

        dataGridView1.Columns[4].Name = "Amount";
        dataGridView1.Columns[4].HeaderText = "Amount";
        // dataGridView1.Columns[4].DataPropertyName = "product_Name";

        dataGridView1.Columns[5].Name = "Discount";
        dataGridView1.Columns[5].HeaderText = "Discount";
        //dataGridView1.Columns[5].DataPropertyName = "product_Name";

        dataGridView1.Columns[6].Name = "Sub-Total";
        dataGridView1.Columns[6].HeaderText = "Sub-Total";
        // dataGridView1.Columns[6].DataPropertyName = "product_Name";
        dataGridView1.DataSource = dt;
    }

未获取预定义Datagrid列中的数据

您的SQL查询返回一个列为Product NameActual SP的表,但在您的datagridview中您正在赋值;

dataGridView1.Columns[0].DataPropertyName = "product_Id";

product_Id列不在数据表中。

变更如下:;

dataGridView1.Columns[0].DataPropertyName = "Actual SP";
dataGridView1.Columns[2].DataPropertyName = "Product Name";

那么它应该会起作用。

您必须将每一列添加到DataGridView中,如:

dataGridView1.Columns.Add("ProductId","PID");
dataGridView1.Columns["ProductId"].DataPropertyName="product_Id";