在asp.net中将复选字符串转换为布尔值 [英] Covert string to boolean for checkbox in asp.net

查看:205
本文介绍了在asp.net中将复选字符串转换为布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

* .aspx



 <   asp:templatefield     HeaderText   =  >  
< itemtemplate >
< asp:CheckBox ID = ckbValue runat = server 已选中 = ' <% #Eval( szValue)== DBNull.Value? false :Convert.ToBoolean(Eval( szValue))|| Eval( szDefaultValue)== DBNull.Value? false :Convert.ToBoolean(Eval( szDefaultValue))%> ' CssClass = pkchkbox > < / asp:CheckBox >
< / itemtemplate >
< / asp:templatefield >





* .aspx .cs

  foreach (DataRow row  in  m_dt.Rows)
{
if (row [ 1 ]。 ToString()== Y
{
row [ 1 ] = true ;
}
else if (row [ 1 ]。ToString()== N
row [ 1 ] = false ;
}





我要转换将显示在一个复选框中的szValue和szDefaultValue。

但它不起作用。

帮助我解决我的问题。 thankyou

解决方案

引用:

但它不起作用



这不是很有用。你应该详细说明。



你的代码不健全,你可能需要处理 null 值,可能你有修剪检索到的字符串,可能你必须处理YN一切else


Convert.ToBoolean不能解释任何字符串 - 事实上它使用Boolean.Parse,它有'True'和'False'作为字符串来解释(不区分大小写) )...

要将其他字符串转换为布尔值,您必须编写自己的代码...一个选项是

  bool  bVal =   Y .Equals(orgValue, StringComparison.OrdinalIgnoreCase); 


*.aspx

<asp:templatefield HeaderText="Value">
    <itemtemplate>
        <asp:CheckBox ID="ckbValue" runat="server" Checked='<%# Eval("szValue") == DBNull.Value ? false : Convert.ToBoolean(Eval("szValue")) || Eval("szDefaultValue") == DBNull.Value ? false : Convert.ToBoolean(Eval("szDefaultValue"))%>' CssClass="pkchkbox" ></asp:CheckBox>
    </itemtemplate>
</asp:templatefield>



*.aspx.cs

foreach (DataRow row in m_dt.Rows)
          {
              if (row[1].ToString() == "Y")
              {
                  row[1] = true;
                                  }
              else if (row[1].ToString() == "N")
                  row[1] = false;
          }



I wan to convert szValue and szDefaultValue that will display in one checkbox.
But it's not work.
Help me to solve my problem. thankyou

解决方案

Quote:

But it's not work


That's not pretty informative. You should detail.

Your code is not robust, possibly you need to handle null values, possibly you have to trim the retrieved string, possibly you have to handle both "Y", "N" and everything else.


Convert.ToBoolean can not interpret any string - in fact it uses Boolean.Parse which have 'True' and 'False' as strings to interpret (case-insensitive)...
To convert other strings to Boolean you have to write your own code...One option is

bool bVal = "Y".Equals(orgValue, StringComparison.OrdinalIgnoreCase);


这篇关于在asp.net中将复选字符串转换为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆