DataGridView列模板 [英] DataGridView Column Template

查看:77
本文介绍了DataGridView列模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

我在Form上有一个DataGridView,该事件正在Click事件按钮上填充有数据库记录.
如何在运行时以编程方式填充另外两列模板?

两列模板是库存数量状态

这是我的datagridview在单击事件按钮上填充时的样子...

Hello Everyone

I have a DataGridView on my Form which is being populated with database records on the click event button.
How can I populate another two column template programatically at run time?

The two column template are Qty In Stock and Status

This is my datagridview what looks like when populated on click event button...

===============================================================
FoodName        FoodType     Qty In Stock     Status
===============================================================
Olives          Starter                     
Soup            Starter                     
Caprese	        Starter
Bruschetta	Starter
Mushroom	Starter
Antipasto	Starter
Scallops	Starter
Calamari	Starter
Crab Avocado	Starter
Pizza Bread	Starter
===============================================================



这就是datagridview我想要的样子



And this is datagridview what I want to look like

=================================================================
FoodName        FoodType     Qty In Stock     Status
=================================================================
Olives          Starter      0                Allways On Stock
Soup            Starter      0                Allways On Stock
Caprese	        Starter      0                Allways On Stock
Bruschetta	Starter      0                Allways On Stock
Mushroom	Starter      0                Allways On Stock
Antipasto	Starter      0                Allways On Stock
Scallops	Starter      0                Allways On Stock
Calamari	Starter      0                Allways On Stock
Crab Avocado	Starter      0                Allways On Stock
Pizza Bread	Starter      0                Allways On Stock
=================================================================



这是在单击事件按钮上填充的datagridview的代码...



Here the code of datagridview populated on click event button...

private DataGridViewTextBoxColumn ColFoodQtyStock = new DataGridViewTextBoxColumn();
        private DataGridViewTextBoxColumn ColFoodStatus = new DataGridViewTextBoxColumn();

        private void cmdStarters_Click(object sender, EventArgs e)
        {
            OleDbConnectionStringBuilder connBuilder = new OleDbConnectionStringBuilder();
            connBuilder.DataSource = @"C:\Users\AP_AE\Desktop\DTPOS_APP\DataBase\DtposMenu.accdb";
            connBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
            connBuilder.Add("Jet OLEDB:Engine Type", "5");

            // Food SQL Query
            string foodTypeSql = @"SELECT FoodName, FoodType FROM Food WHERE FoodType = @foodType";
            using (OleDbConnection conn = new OleDbConnection(connBuilder.ConnectionString))
            {
                dataGridView1.Columns.Clear();
                dataGridView1.RowTemplate.Height = 60;
                //====================================\\
                dataGridView1.Visible = true;
                dataGridView2.Visible = false;
                try
                {
                    OleDbCommand foodsCommand = new OleDbCommand(foodTypeSql, conn);
                    OleDbParameter foodType = foodsCommand.Parameters.Add("@foodType", OleDbType.VarChar, 15);
                    OleDbDataAdapter foodsDa = new OleDbDataAdapter(foodsCommand);
                    //DataRow dr;
                    DataSet ds = new DataSet();
                    conn.Open();
                    foodType.Value = "Starter";
                    foodsDa.Fill(ds, "Food_table");
                    
                    conn.Close();
                    dataGridView1.DataSource = ds;
                    dataGridView1.DataMember = "Food_table";

                    dataGridView1.Columns.AddRange(ColFoodQtyStock, ColFoodStatus);
                    
                    DataGridViewCellStyle dataGridViewCellStyle1 = new DataGridViewCellStyle();
                    this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
                    dataGridViewCellStyle1.Font = new Font("Verdana", 20.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                    this.dataGridView1.Columns[0].Width = 420;
                    this.dataGridView1.Columns[1].Width = 180;
                    this.dataGridView1.Columns[2].Width = 300;
                    this.dataGridView1.Columns[3].Width = 308;

                    // ColStatus 
                    ColFoodStatus.HeaderText = "Status";
                    ColFoodStatus.Name = "ColFoodStatus";

                    // ColQtyStock
                    ColFoodQtyStock.HeaderText = "Quantity In Stock";
                    ColFoodQtyStock.Name = "ColFoodQtyStock";

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex);
                }
            }
        }



有人可以帮我解决这个问题吗

在此先感谢


lapeci



Could someone help me to solve this problem please

Thanks in advance


lapeci

推荐答案

我认为您可以在数据源(数据集或数据库中)中生成默认值(用于库存数量",状态").那么您可以与Datagridview绑定.

看看这些(也涉及动态列的创建)


101种操作DataGridView控件的方法-第1部分
[ ^ ]

101种操作DataGridView控件的方法-第2部分 [
在应用程序的form_load中调用以下方法.
I think you can generate the default values(for Columns Qty In Stock, Status) in your datasource(In dataset or database) & then you can bind with Datagridview.

Have a look at these (Involves dynamic columns creation too)


101 Ways to Manipulate the DataGridView Control - Part 1
[^]

101 Ways to Manipulate the DataGridView Control - Part 2[^]


I think you forgot to fill the value for DataPropertyName property, so assign the value for Design columns + runtime columns.

Call the below method in form_load in your application.
public void BindGridView()
{
    DataTable table = new DataTable();
    table.Columns.Add("FoodName", typeof(string));
    table.Columns.Add("FoodType", typeof(string));
    table.Columns.Add("QtyInStock", typeof(int));
    table.Columns.Add("Status", typeof(string));
    string[] arrFoodName = new string[] { "Olives", "Soup", "Caprese", "Bruschetta", "Mushroom", "Antipasto", "Scallops", "Calamari", "Crab Avocado", "Pizza Bread" };
    string[] arrFoodType = new string[] { "Starter", "Other" };
    bool IsStock = false;
    long Qty = 0;
    for (int i = 0; i < 10; i++)
    {
        if (i > 5)
        {
            Qty = i * 5;
            IsStock = true;
        }
        if (IsStock)//A dummy condition to check the stock status
        {
            table.Rows.Add(arrFoodName[i], arrFoodType[1], Qty, "Always On Stock");
        }
        else
        {
            table.Rows.Add(arrFoodName[i], arrFoodType[0], 0, "No Stock");
        }
    }
    dataGridView1.AutoGenerateColumns = false;
    dataGridView1.DataSource = table;

    DataGridViewTextBoxColumn ColFoodQtyStock = new DataGridViewTextBoxColumn();
    DataGridViewTextBoxColumn ColFoodStatus = new DataGridViewTextBoxColumn();

    ColFoodStatus.HeaderText = "Status";
    ColFoodStatus.DataPropertyName = "Status";//You forgot to fill this one
    ColFoodStatus.Name = "Status";

    ColFoodQtyStock.HeaderText = "Quantity In Stock";
    ColFoodQtyStock.DataPropertyName = "QtyInStock";//You forgot to fill this one
    ColFoodQtyStock.Name = "QtyInStock";
    dataGridView1.Columns.AddRange(ColFoodQtyStock, ColFoodStatus);
}


现在它将显示四列数据.
注意:请与您的列名一起使用.

用于添加动态列的示例&行到数据表


Now It will display four columns with data.
Note : check the column names mine with yours.

Sample for adding dynamic columns & rows to datatable

DataTable dt = new DataTable();
DataRow myNewRow;
myNewRow = dt.NewRow();
myNewRow.Table.Columns.Add("QtyInStock");
myNewRow.Table.Columns.Add("Status");
myNewRow["QtyInStock"] = 1;
myNewRow["Status"] = "No Stock" ;
dt.Rows.Add(myNewRow);




[最终编辑]
如果您希望新生成的运行时列(QtyInStock和状态)的默认值始终为0,则总是库存",然后更改查询dude.




[Final EDIT]
If you want the 0, "Always on Stock" as default for your newly generated run time columns(QtyInStock & Status) then change the query dude.

string foodTypeSql = @"SELECT FoodName, FoodType, 0 AS QtyInStock, 'Always on Stock' AS Status FROM Food WHERE FoodType = @foodType";


) 您可以 CASE语句 [


You can CASE statement[^] for defining the row values based on conditions. That''s it.
[/Final EDIT]


BTW I''m glad you came with good question with your snippet(I like the style of your question), please keep continue always dude.

Cheers. :thumbsup:


这篇关于DataGridView列模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆