检查数据库c#/ .net中是否存在值

时间:2015-04-13 13:59:14

标签: c# html .net checkbox

我将表单数据发送到sql数据库,然后以另一种形式显示我的用户的输出。我刚刚添加了一个复选框字段,我将值设置为'Y'和'N'表示是和否。我能够保存并检索它,但我试图将该值绑定到表单中的复选框字段。

所以我的问题是如何在复选框字段中显示数据库中该特定项目的字段值?

这是我到目前为止所做的事情并没有奏效:

private void LoadData()
{
    Connection connection = new Connection();
    try
    {
        connection.connection1();
        SqlCommand com = new SqlCommand("Select Image,UserName,Description,Private,CompValue FROM FutureProjTbl Where id='" + projectId + "'", connection.con);
        SqlDataReader dataReader = com.ExecuteReader();

        while (dataReader.Read())
        {
            image1.Src = dataReader["Image"].ToString();
            Owner.Text = dataReader["UserName"].ToString();
            Description.Text = dataReader["Description"].ToString();
            //The following 2 are my attempts to retrieve the item and bind it to the checkbox on the project template all the values will load into.
            //privateItem.Checked = Convert.ToBoolean(dataReader["Private"].ToString());
            //privateItem = (CheckBox) dataReader["Private"];
            compValue.Text = dataReader["CompValue"].ToString();


            FillDataForEditProjectModal(dataReader);
        }
        dataReader.Close();
    }
    catch (Exception)
    {

        throw;
    }
}

enter image description here

2 个答案:

答案 0 :(得分:3)

您需要比较并返回一个布尔值来设置选中的值

privateItem.Checked = (dataReader["Private"].ToString() == "Y");

答案 1 :(得分:2)

试试这个:

privateItem.Checked = dataReader["Private"] == null ? false : dataReader["Private"].ToString() == "Y";

但是,不是将值存储为YN,为什么不将该字段更改为数据库中的bool,然后您可以将其保存为复选框的选中状态(即{{ 1}}用于trueY用于false),当您将其恢复时,它会更容易映射:

N