smile says:
<
asp:BoundField
DataField
=
'+@cols +'
HeaderText
=
"'+@cols+'"
/>
No you cant pass columnname line this.
You need to first set AutoGenerateColumns="false" for GridView and remove the columns you added in gridview.
Then add BoundField columns based on the DataTable Columns.
Then you can check the condition for hiding the null columns.
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
</asp:GridView>
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[] { new DataColumn("Name", typeof(string)), new DataColumn("City", typeof(string)), new DataColumn("Country", typeof(string)) });
dt.Rows.Add("Ram", "Mumbai", "");
dt.Rows.Add("Rahim", "Rampur", null);
dt.Rows.Add("Abdul", "Lucknow", "");
GridView1.DataSource = dt;
GridView1.Columns.Clear();
foreach (DataColumn column in dt.Columns)
{
BoundField field = new BoundField();
field.DataField = column.ColumnName;
field.HeaderText = column.ColumnName;
GridView1.Columns.Add(field);
}
GridView1.DataBind();
for (int i = 0; i < GridView1.Columns.Count; i++)
{
bool allRowNull = true;
for (int j = 0; j < GridView1.Rows.Count; j++)
{
string text = GridView1.Rows[j].Cells[i].Text;
if (text != " ")
{
allRowNull = false;
break;
}
}
if (allRowNull)
{
GridView1.Columns[i].Visible = false;
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn() {
New DataColumn("Name", GetType(String)),
New DataColumn("City", GetType(String)),
New DataColumn("Country", GetType(String))
})
dt.Rows.Add("Ram", "Mumbai", "")
dt.Rows.Add("Rahim", "Rampur", Nothing)
dt.Rows.Add("Abdul", "Lucknow", "")
GridView1.DataSource = dt
GridView1.Columns.Clear()
For Each column As DataColumn In dt.Columns
Dim field As BoundField = New BoundField()
field.DataField = column.ColumnName
field.HeaderText = column.ColumnName
GridView1.Columns.Add(field)
Next
GridView1.DataBind()
For i As Integer = 0 To GridView1.Columns.Count - 1
Dim allRowNull As Boolean = True
For j As Integer = 0 To GridView1.Rows.Count - 1
Dim text As String = GridView1.Rows(j).Cells(i).Text
If text <> " " Then
allRowNull = False
Exit For
End If
Next
If allRowNull Then
GridView1.Columns(i).Visible = False
End If
Next
End If
End Sub
Screenshot