How to Hide a Datagrid Column in C#

I was developing another windows mobile which has the requirement of using a datagrid for dataview. A DataGrid is a good control in presenti...

I was developing another windows mobile which has the requirement of using a datagrid for dataview. A DataGrid is a good control in presenting your data [].

It has many customizable properties which you can see to fit your need, for example you can change the Columns bound in the datagrid. There are TextBox, Boolean, etc DataGrid column.

Unfortunately for windows mobile [CF1.1] the only available column type is DataGridTextBoxColumn [].

Nevertheless I want, to customize the look: set the width, change the column header, etc. Let's try these 2 basic customization.

First we should setup the DataGridTableStyle, please follow the code (In this example we are customizing 3 columns, the first 1 is the ID):

col1, col2 - datagrid columns, 
           - name should much the data row you have queried
head1, head2 - datagrid column header text
private void UpdateGridStyle(DataGrid grid, string col1, 
        string col2, string head1, 
        string head2) {
 //first we will clear the tablestyles, 
 //if not it will throw argument exception
 //if there is already a style prior to this call
 DataGridTableStyle tableStyle = new DataGridTableStyle(); 
 //take note of this mapping name, it's very important
 tableStyle.MappingName = "czetsuya"; 

 //our first column which is the ID
 DataGridTextBoxColumn gridColumn1 = new DataGridTextBoxColumn();
 gridColumn1.Width = 0;
 gridColumn1.MappingName = "ID";
 gridColumn1.HeaderText = "ID";

 //second column
 DataGridTextBoxColumn gridColumn2 = new DataGridTextBoxColumn();
 gridColumn2.Width = 100;
 gridColumn2.MappingName = col1;
 gridColumn2.HeaderText = head1;

 //third column
 DataGridTextBoxColumn gridColumn3 = new DataGridTextBoxColumn();
 gridColumn3.Width = 100;
 gridColumn3.MappingName = col2;
 gridColumn3.HeaderText = head2;

public DataTable QueryAsDataTable(string sql) {
 DataTable dt = new DataTable();
  SqlCeDataAdapter da = new SqlCeDataAdapter(sql, conn);
 catch(SqlCeException e) 
  //catch exception
 //TAKE NOTE OF THIS MAPPING, without this the code will not work
 //this mapping will be reference by the DataGridTableStyle
 dt.TableName = "czetsuya"; 
 return dt;
//we will call the above functions like this:

sql = "SELECT field1 AS ID, field2 AS col1, field3 AS col2 
       FROM table";
UpdateGridStyle("col1", "col2", "COLUMN1", "COLUMN1");
grid.DataSource = da.QueryAsDataTable(sql);


c# 1094818433378434099

Post a Comment Default Comments


Anonymous said...

I'm appreciate your writing skill.Please keep on working hard.^^

Anonymous said...

Thank you very much from bottom of heart