【问题标题】:How to select all fields but show certain in DataGridView in C#如何选择所有字段但在 C# 的 DataGridView 中显示某些字段
【发布时间】:2017-06-06 13:18:06
【问题描述】:

我在 c# windows 窗体 App 中显示 DataGridView 上的一些数据。在这里我要选择 ID,因为我必须将其用作外键,但我不想在网格上显示该 ID 字段。

 using (SqlConnection con = new SqlConnection(constr))
            {
                con.Open();
                using (SqlCommand command = new SqlCommand("select * from PatientInfo", con))
                {
                    SqlDataReader reader = command.ExecuteReader();
                    if (reader.HasRows)
                    {
                        DataTable dt = new DataTable();
                        dt.Load(reader);
                        datagridpatient.DataSource = dt;
                        con.Close();
                    }
                }
            }

我只想显示姓名、电子邮件、电话。同时为了进一步使用我也需要选择ID。

【问题讨论】:

    标签: c# sql .net datagridview


    【解决方案1】:

    您可以隐藏该列,

    dataGridView.Columns["ColumnName"].Visible = false;

    例如:

        using (SqlConnection con = new SqlConnection(constr))
             {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                    using (SqlCommand command = new SqlCommand("select * from PatientInfo", con))
                    {
                        SqlDataReader reader = command.ExecuteReader();
                        if (reader.HasRows)
                        {
                            DataTable dt = new DataTable();
                            dt.Load(reader);
                            datagridpatient.DataSource = dt;
                            if (datagridpatient.Columns.Contains("ID")
                               datagridpatient.Columns["ID"].Visible = false;
                            con.Close();
                        }
                    }
                }
             }
    

    【讨论】:

    • Bang-on.. 谢谢朋友
    • 通过验证连接状态@SidraM 编辑了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多