winform datagridview 手动绑定列

时间:2022-08-20 19:46:46

/// <summary>
        /// 根据好友获取好友动态
        /// </summary>
        public void getAction()
        {
            List<FriendActioninfo> finfo = friendinfo.GetActionByFriendId(FuserId);
            dgvFUserAction.DataSource = finfo;
            dgvFUserAction.Columns.Clear();
            DisplayCol(dgvFUserAction, "Title", "标题");
            DisplayCol(dgvFUserAction, "Context", "内容");
            dgvFUserAction.Visible = true;
            lblFriendUserid.Visible = true;
        }

        /// <summary>  
        /// 设置列 
        /// </summary>  
        /// <param name="dgv">DataGridview控件</param>  
        /// <param name="dataPropertyName">绑定的数据名</param>  
        /// <param name="headerText">标头标题</param>  
        private void DisplayCol(DataGridView dgv, String dataPropertyName, String headerText)
        {
            dgv.AutoGenerateColumns = false;
            DataGridViewTextBoxColumn obj = new DataGridViewTextBoxColumn();
            obj.DataPropertyName = dataPropertyName;
            obj.HeaderText = headerText;
            obj.Name = dataPropertyName;
            obj.Resizable = DataGridViewTriState.True;
            dgv.Columns.AddRange(new DataGridViewColumn[] { obj });
        }