Search This Blog

Wednesday, September 1, 2010

Hide GridView column using javascript

GridView Markup

<script language="JavaScript">
function hideColumn()
{
col_num = document.getElementById("column_numbder").value;
rows = document.getElementById("GridView1").rows;
for(i=0;i <rows.length;i++)
{
rows[i].cells[col_num].style.display="none";
}
}
</script>

<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
<input id="column_numbder" type="text">
<input type="button" value="Hide" onclick="hideColumn()">
</form>
</body>

Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["strTemp"] != null)
{
GridView1.DataSource = Session["strTemp"] as DataTable;
GridView1.DataBind();
}
else
{
GridView1.DataSource = GetCustomMadeDataTable();
GridView1.DataBind();
}
}
}
public DataTable GetCustomMadeDataTable()
{
//Create a new DataTable object
System.Data.DataTable objDataTable = new System.Data.DataTable();
//Create three columns with string as their type
objDataTable.Columns.Add("Id", typeof(string));
objDataTable.Columns.Add("Column1", typeof(string));
objDataTable.Columns.Add("Column2", typeof(string));
objDataTable.Columns.Add("Column3", typeof(string));
//Adding some data in the rows of this DataTable
DataRow dr;
for (int i = 0; i <= 20; i++)
{
dr = objDataTable.NewRow();
dr[0] = i.ToString();
dr[1] = "Column1Data" + i.ToString();
dr[2] = "Column2Data" + i.ToString();
dr[3] = "Column3Data" + i.ToString();
objDataTable.Rows.Add(dr);
DataColumn[] dcPk = new DataColumn[1];
dcPk[0] = objDataTable.Columns["Id"];
objDataTable.PrimaryKey = dcPk;
Session["strTemp"] = objDataTable;
return objDataTable;
}


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.