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

时间:2015-12-23 04:50:50

标签: c# datagrid

我有一个预定义的datagrid列,它在表单加载时加载。我想要的是当我在文本框中输入产品的id或名称时,我希望它在datagrid列中显示。但是当我输入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;

    }

2 个答案:

答案 0 :(得分:2)

您的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";

然后它应该工作。

答案 1 :(得分:0)

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

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