0

我是 C# 程序员。目前,我正在尝试在 datagrid-viewer 的 sql 数据中添加 5 列中的 3 列(fileId、filePath、authorName、fileContent、DateSend);fileId 和 fileContent 列是隐藏的。非常感谢!

        con = new SqlConnection("Data Source=LEO-PC\\SQLEXPRESS;Initial Catalog = datashare;Integrated Security = True");
        cmd = new SqlCommand("select * from maintable", con);
        con.Open();
        SqlDataReader sqlRead;
        try
        {
            sqlRead = cmd.ExecuteReader();
            while (sqlRead.Read())
            {
               //Adding to datagrid
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            con.Close();
        }
4

1 回答 1

0

要隐藏 2 个字段,请在网格中创建一个 OnRowCreated 事件:

OnRowCreated="gridView1_RowCreated"

请记住使用

SqlDataReader reader = cmd.ExecuteReader();     
gridView1.DataSource = reader; 

并且gridview必须有属性必须是AutoGeneretedColumns = "true"

然后按如下方式创建事件:

protected void gridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
            if (e.Row.RowType == DataControlRowType.Header)
            {
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    DataControlFieldCell cell =
                        (DataControlFieldCell) e.Row.Cells[i];


                    if (cell.ContainingField.HeaderText == "fileId")
                    {
                        e.Row.Cells[i].Visible = false;
                        cell.Visible = false;
                    }

                    if (cell.ContainingField.HeaderText == "fileContent")
                    {
                        e.Row.Cells[i].Visible = false;
                        cell.Visible = false;
                    }
                }
            }

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                for (int i = 0; i < e.Row.Cells.Count; i++)
                {
                    DataControlFieldCell cell =
                        (DataControlFieldCell) e.Row.Cells[i];

                    if (cell.ContainingField.ToString() == "fileId")
                    {
                        cell.Visible = false;
                    }

                    if (cell.ContainingField.ToString() == "fileContent")
                    {
                        cell.Visible = false;
                    }
                }
            }
}

这可能不是最有效的方式,但它使用代码来达到目的。绑定列时,应该能够使用 gridview 模板隐藏列。

于 2012-08-15T06:57:19.973 回答