我想在GridView中隐藏ID列,我知道代码
GridView1.Columns[0].Visible = false;
但令人惊讶的是我的GridView
列的计数属性为0!虽然我可以在GridView
看到数据,所以有什么想法吗?
谢谢,
更新
这是填充GridView
public DataSet GetAllPatients()
{
SqlConnection connection = new SqlConnection(this.ConnectionString);
String sql = "SELECT [ID],[Name],[Age],[Phone],[MedicalHistory],[Medication],[Diagnoses] FROM [dbo].[AwadyClinc_PatientTbl]order by ID desc";
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
答案 0 :(得分:60)
GridView.Columns.Count
属性设置为AutoGenerateColumns
时, true
将始终为0(默认为true
)。
您可以显式声明列并将AutoGenerateColumns
属性设置为false
,也可以在代码隐藏中使用它:
GridView.Rows[0].Cells.Count
在绑定GridView数据后获取列计数,或者:
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Cells[index].Visible = false;
}
使用GridView的RowDataBound
事件将列设置为不可见。
答案 1 :(得分:26)
这对我有帮助
this.myGridview.Columns[0].Visible = false;
这里0是我要隐藏的列索引。
答案 2 :(得分:22)
您可以通过查询datacontrolfield集合以查找所需的列标题文本并将其可见性设置为true来隐藏特定列。
((DataControlField)gridView.Columns
.Cast<DataControlField>()
.Where(fld => (fld.HeaderText == "Title"))
.SingleOrDefault()).Visible = false;
答案 3 :(得分:11)
我见过的一些答案解释了如何使单元格的内容不可见,而不是如何隐藏整个列,这就是我想要做的。
如果您有AutoGenerateColumns = "false"
并且实际上正在使用BoundField
作为要隐藏的列,则Bala的answer是光滑的。但是,如果您使用TemplateField
作为列,则可以处理DataBound
事件并执行以下操作:
protected void gridView_DataBound(object sender, EventArgs e)
{
const int countriesColumnIndex = 4;
if (someCondition == true)
{
// Hide the Countries column
this.gridView.Columns[countriesColumnIndex].Visible = false;
}
}
这可能不是OP所期待的,但当我发现自己提出同样的问题时,这是我正在寻找的解决方案。
答案 4 :(得分:2)
如果你想在网格填充时隐藏该列,你可以在aspx页面本身这样做
<asp:BoundField DataField="test" HeaderText="test" Visible="False" />
答案 5 :(得分:2)
这里我用这样的数据集绑定gridview -
GVAnswer.DataSource = DS.Tables[0];
GVAnswer.DataBind();
然后
然后我们计算行数 像for循环一样
for (int i = 0; i < GVAnswer.Rows.Count; i++)
{
}
然后在我们找到标题之后我们想要显示为假
GVAnswer.HeaderRow.Cells[2].Visible = false;
然后我们将该特定单元格的可见性设为假。
完整的代码就像这样给出
public void FillGVAnswer(int QuestionID)
{
try
{
OBJClsQuestionAnswer = new ClsQuestionAnswer();
DS = new DataSet();
DS = OBJClsQuestionAnswer.GetAnswers(QuestionID);
GVAnswer.DataSource = DS.Tables[0];
GVAnswer.DataBind();
if (DS.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < GVAnswer.Rows.Count; i++)
{
GVAnswer.HeaderRow.Cells[2].Visible = false;
GVAnswer.HeaderRow.Cells[3].Visible = false;
GVAnswer.HeaderRow.Cells[6].Visible = false;
GVAnswer.HeaderRow.Cells[8].Visible = false;
GVAnswer.HeaderRow.Cells[10].Visible = false;
GVAnswer.HeaderRow.Cells[11].Visible = false;
//GVAnswer.Rows[i].Cells[1].Visible = false;
if (GVAnswer.Rows[i].Cells[4].Text == "T")
{
GVAnswer.Rows[i].Cells[4].Text = "Text";
}
else
{
GVAnswer.Rows[i].Cells[4].Text = "Image";
}
if (GVAnswer.Rows[i].Cells[5].Text == "View Image")
{
HtmlAnchor a = new HtmlAnchor();
a.HRef = "~/ImageHandler.aspx?ACT=AIMG&AID=" + GVAnswer.Rows[i].Cells[2].Text;
a.Attributes.Add("rel", "lightbox");
a.InnerText = GVAnswer.Rows[i].Cells[5].Text;
GVAnswer.Rows[i].Cells[5].Controls.Add(a);
}
if (GVAnswer.Rows[i].Cells[7].Text == "Yes")
{
j++;
ViewState["CheckHasMulAns"] = j;// To Chek How Many answer Of a particulaer Question Is Right
}
GVAnswer.Rows[i].Cells[8].Visible = false;
GVAnswer.Rows[i].Cells[3].Visible = false;
GVAnswer.Rows[i].Cells[10].Visible = false;
GVAnswer.Rows[i].Cells[6].Visible = false;
GVAnswer.Rows[i].Cells[11].Visible = false;
GVAnswer.Rows[i].Cells[2].Visible = false;
}
}
}
catch (Exception ex)
{
string err = ex.Message;
if (ex.InnerException != null)
{
err = err + " :: Inner Exception :- " + ex.InnerException.Message;
}
string addInfo = "Error in getting Answers :: -> ";
ClsExceptionPublisher objPub = new ClsExceptionPublisher();
objPub.Publish(err, addInfo);
}
}
答案 6 :(得分:2)
private void Registration_Load(object sender, EventArgs e)
{
//hiding data grid view coloumn
datagridview1.AutoGenerateColumns = true;
datagridview1.DataSource =dataSet;
datagridview1.DataMember = "users"; // users is table name
datagridview1.Columns[0].Visible = false;//hiding 1st coloumn coloumn
datagridview1.Columns[2].Visible = false; hiding 2nd coloumn
datagridview1.Columns[3].Visible = false; hiding 3rd coloumn
//end of hiding datagrid view coloumns
}
}
答案 7 :(得分:2)
如果要在GridView中按名称而不是其索引隐藏列。在创建DataTable或Dataset之后,您必须按名称查找列的索引,然后将索引保存在全局变量中,如ViewStae,Session等,然后在RowDataBound中调用它,如示例所示:
string headerName = "Id";
DataTable dt = .... ;
for (int i=0;i<dt.Columns.Count;i++)
{
if (dt.Columns[i].ColumnName == headerName)
{
ViewState["CellIndex"] = i;
}
}
... GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Footer)
{
int index = Convert.ToInt32(ViewState["CellIndex"]);
e.Row.Cells[index].Visible = false;
}
}
答案 8 :(得分:2)
这里的大多数答案都不能解释 - 如果您需要再次显示列并且不可见,那么所有这些都是基于动态数据的?毕竟,不应该GridViews
以数据为中心吗?
如果您想根据数据打开或关闭列,该怎么办?
我的Gridview
<asp:GridView ID="gvLocationBoard" runat="server" AllowPaging="True" AllowSorting="True" ShowFooter="false" ShowHeader="true" Visible="true" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333" GridLines="None"
DataSourceID="sdsLocationBoard" OnDataBound="gvLocationBoard_DataBound" OnRowDataBound="gvLocationBoard_RowDataBound" PageSize="15" OnPreRender="gvLocationBoard_PreRender">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="StudentID" SortExpression="StudentID" Visible="False">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("StudentID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student" SortExpression="StudentName">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("StudentName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" SortExpression="CheckStatusName" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:HiddenField ID="hfStatusID" runat="server" Value='<%# Eval("CheckStatusID") %>' />
<asp:Label ID="Label4" runat="server" Text='<%# Eval("CheckStatusName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RollCallPeriod0" Visible="False">
<ItemTemplate>
<asp:CheckBox ID="cbRollCallPeriod0" runat="server" />
<asp:HiddenField ID="hfRollCallPeriod0" runat="server" Value='<%# Eval("RollCallPeriod") %>' />
</ItemTemplate>
<HeaderStyle Font-Size="Small" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="RollCallPeriod1" Visible="False">
<ItemTemplate>
<asp:CheckBox ID="cbRollCallPeriod1" runat="server" />
<asp:HiddenField ID="hfRollCallPeriod1" runat="server" Value='<%# Eval("RollCallPeriod") %>' />
</ItemTemplate>
<HeaderStyle Font-Size="Small" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
..
etc..
请注意`&#34; RollCallPeriodn&#34;,其中&#39; n&#39;是序号。
我这样做的方法是设计隐藏所有列,我知道它们将会打开(可见=&#34; true&#34;)或OFF(可见=&# 34;假&#34;)以后,取决于我的数据。
在我的情况下,我想将Period Times显示到某个列。例如,如果今天是上午9点,那么我想显示上午6点,早上7点,早上8点和上午9点,但不是上午10点,上午11点等。
在其他日子里,我想要一直展示。等等。
那我们该怎么办?
为什么不使用PreRender
来&#34;重置&#34; Gridview
?
protected void gvLocationBoard_PreRender(object sender, EventArgs e)
{
GridView gv = (GridView)sender;
int wsPos = 3;
for (int wsCol = 0; wsCol < 19; wsCol++)
{
gv.Columns[wsCol + wsPos].HeaderText = "RollCallPeriod" + wsCol.ToString("{0,00}");
gv.Columns[wsCol + wsPos].Visible = false;
}
}
现在根据找到HeaderText的开头打开所需的列,如果标题文本不是默认值,则将列显示为。
protected void gvLocationBoard_DataBound(object sender, EventArgs e)
{
//Show the headers for the Period Times directly from sdsRollCallPeriods
DataSourceSelectArguments dss = new DataSourceSelectArguments();
DataView dv = sdsRollCallPeriods.Select(dss) as DataView;
DataTable dt = dv.ToTable() as DataTable;
if (dt != null)
{
int wsPos = 0;
int wsCol = 3; //start of PeriodTimes column in gvLocationBoard
foreach (DataRow dr in dt.Rows)
{
gvLocationBoard.Columns[wsCol + wsPos].HeaderText = dr.ItemArray[1].ToString();
gvLocationBoard.Columns[wsCol + wsPos].Visible = !gvLocationBoard.Columns[wsCol + wsPos].HeaderText.StartsWith("RollCallPeriod");
wsPos += 1;
}
}
}
我在这里不会透露SqlDataSource
,但只需说明PreRender
,我就可以重置GridView
并使用标题打开我想要的列我想。
所以它的工作方式是每当你选择一个不同的日期或时间段来显示为标题时,它会将GridView重置为默认的标题文本和Visible =&#34; false&#34;在再次构建gridview
之前的状态。否则,如果没有PreRender
,GridView将使用以前的数据标题,因为后面的代码会清除默认设置。
答案 9 :(得分:0)
请使用此代码。如果为空,这会产生不可见的列...
protected void gridview1_DataBound(object sender, EventArgs e)
{
Boolean hasData = false;
for (int col = 0; col < gridview1.HeaderRow.Cells.Count; col++)
{
for (int row = 0; row < gridview1.Rows.Count; row++)
{
if (!String.IsNullOrEmpty(gridview1.Rows[row].Cells[col].Text)
&& !String.IsNullOrEmpty(HttpUtility.HtmlDecode(gridview1.Rows[row].Cells[col].Text).Trim()))
{
hasData = true;
break;
}
}
if (!hasData)
{
gridview1.HeaderRow.Cells[col].Visible = false;
for (int hiddenrows = 0; hiddenrows < gridview1.Rows.Count; hiddenrows++)
{
gridview1.Rows[hiddenrows].Cells[col].Visible = false;
}
}
hasData = false;
}
}
答案 10 :(得分:0)
发生了一个很小的变化,它不会出现在rowdatabound之下,首先所有行都应该绑定,然后我们才能隐藏它。因此,在网格为dataBound之后,它将是一个单独的方法。
答案 11 :(得分:0)
当列Id未知且AutoGenerateColumns == true时,这是代码对我有用;
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Drawing" %>
<html>
<head runat="server">
<script runat="server">
protected void Page_Load(object sender, EventArgs eventArgs)
{
DataTable data = new DataTable();
data.Columns.Add("Id", typeof(int));
data.Columns.Add("Notes", typeof(string));
data.Columns.Add("RequestedDate", typeof(DateTime));
for (int idx = 0; idx < 5; idx++)
{
DataRow row = data.NewRow();
row["Id"] = idx;
row["Notes"] = string.Format("Note {0}", idx);
row["RequestedDate"] = DateTime.Now.Subtract(new TimeSpan(idx, 0, 0, 0, 0));
data.Rows.Add(row);
}
listData.DataSource = data;
listData.DataBind();
}
private void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (TableCell tableCell in e.Row.Cells)
{
DataControlFieldCell cell = (DataControlFieldCell)tableCell;
if (cell.ContainingField.HeaderText == "Id")
{
cell.Visible = false;
continue;
}
if (cell.ContainingField.HeaderText == "Notes")
{
cell.Width = 400;
cell.BackColor = Color.Blue;
continue;
}
if (cell.ContainingField.HeaderText == "RequestedDate")
{
cell.Width = 130;
continue;
}
}
}
</script>
</head>
<body>
<form runat="server">
<asp:GridView runat="server" ID="listData" AutoGenerateColumns="True" HorizontalAlign="Left"
PageSize="20" OnRowDataBound="GridView_RowDataBound" EmptyDataText="No Data Available."
Width="95%">
</asp:GridView>
</form>
</body>
</html>
答案 12 :(得分:0)
由于您要隐藏列,因此您始终可以在gridview的preRender事件中隐藏该列。这有助于您为每行的每个rowdatabound事件减少一个操作。您只需要一个prerender事件操作。
protected void gvVoucherList_PreRender(object sender, EventArgs e)
{
try
{
int RoleID = Convert.ToInt32(Session["RoleID"]);
switch (RoleID)
{
case 6: gvVoucherList.Columns[11].Visible = false;
break;
case 1: gvVoucherList.Columns[10].Visible = false;
break;
}
if(hideActionColumn == "ActionSM")
{
gvVoucherList.Columns[10].Visible = false;
hideActionColumn = string.Empty;
}
}
catch (Exception Ex)
{
}
}