PAIP.从DATATABLE动态生成表头

PAIP.从DATATABLE动态生成表头

有时候,从数据库中得到的datatable列太多了,一一绑定到界面上的GRID太麻烦了,可以动态绑定..


 /*
         * 从数据库生成的DATABLE列名为textbox1,textbox2,......
         * title为汉字表头,顺序与  datable 的列后缀(textboxids )顺序一一对应
         */
        int startAutoColumnPosition = 5;  //自动生成列开始位置..前边可以自定义固定列.
        string prefix = "textbox";   //databable里边列名前缀
        private void usermain_Load(object sender, EventArgs e)
        {
            DataTable dt = rec.query();
            this.dataGridView1.DataSource = dt;

        


            //表格标头
            string title="比例,单重,供货时间,备注,合计(KG),最低重量,筋条数,送货时间1,合格数量1,重量1,结算单重1,送货时间2,合格数量2,重量2,结算单重2,送货时间3,合格数量3,重量3,结

算单重3,送货时间4,合格数量4,重量4,结算单重4,送货时间5,,合格数量5,重量5,结算单重5,送货时间6,合格数量6,重量6,结算单重6,送货时间7,,合格数量7,重量7,结算单重7,送货时间8,合格数量8,重

量8,结算单重8,送货时间9,,合格数量9,重量9,结算单重9,送货时间10,合格数量10,重量10,结算单重10";

            //datable column 后缀
            string textboxids = "7,8,9,10,11,12,19,18,17,16,14,15,13,26,25, 24,23,21,22,20,55,57,56 ,48,33,29,32, 27,31,28,30, 41,40,36,39,34,38,35,37, 50,49,44,47,42,46,43,45";

            setTitleOnDataView(title, textboxids);

       
           
        }


   private void setTitleOnDataView(string title, string textboxids)
        {


            int ori=startAutoColumnPosition;
          
//循环生成表头.HeaderText
            foreach (DataGridViewTextBoxColumn item in this.dataGridView1.Columns)
            {
               
                String tltle=setColumnHeaderText(item.DataPropertyName, title, textboxids);
                if(!tltle.Equals("null"))
                {
                    item.HeaderText = tltle;
                    item.DisplayIndex=ori+2;
                  
                }

               startAutoColumnPosition++;
               

            }


//把不需要显示的列头,设置为隐藏
            foreach (DataGridViewTextBoxColumn item in this.dataGridView1.Columns)
            {
                if (item.HeaderText.ToLower().StartsWith("text"))
                    item.Visible = false;


            }


        }

 


   //get ColumnHeaderText
        private string setColumnHeaderText(string DataPropertyName, string title, string textboxids)
        {
            string r = "";
            string[] ides = textboxids.Split(",".ToCharArray());
              string[] titlesArr = title.Split(",".ToCharArray());
            int i=0;
            foreach (string item in ides)
            {

                string id = prefix + item;
              if(id.Equals(DataPropertyName.ToLower()))
              {

                  return titlesArr[i];
              }
              i++;
            }
            return "null";
        }

你可能感兴趣的:(数据库,汉字,动态,title,的)