C# CheckedListBox控件的用法

by jack 11. August 2009 19:56

最近用到checklistbox控件,在使用其过程中,花了较多的时间,这里我收集了其相关的代码段,希望对大家有所帮助。

1.

添加项


checkedListBox1.Items.Add("
蓝色");
checkedListBox1.Items.Add("
红色");
checkedListBox1.Items.Add("
黄色");

 

2.
判断第i项是否选中,选中为true,否则为false


if
checkedListBox1.GetItemChecked(i)

{

     return true;

}

else

{

     return false;

}

 

3.
设置第i项是否选中

checkedListBox1.SetItemChecked(i, true);  //true
改为false为没有选中。

 

4.
设置全选
添加一个名为select_allcheckbox控件,由其控制checkedListBox是全选还是全不选。

private void select_all_CheckedChanged(object sender, EventArgs e)
{
     if(select_all.Checked)

{
          for (int j = 0; j < checkedListBox1.Items.Count; j++)
               checkedListBox1.SetItemChecked(j, true);

}
else

{
for (int j =0; j < checkedListBox1.Items.Count; j++)
      checkedListBox1.SetItemChecked(j, false);

}
}

 

5.

得到全部选中的值 ,并将选中的项的文本组合成为一个字符串。


 string strCollected = string.Empty;

 for (int i = 0; i < checkedListBox1.Items.Count; i++)

 {

      if (checkedListBox1.GetItemChecked(i))

      {

          if (strCollected == string.Empty)

          {

               strCollected = checkedListBox1.GetItemText(

checkedListBox1.Items[i]);

          }

          else

          {

               strCollected = strCollected + "/" + checkedListBox1.

GetItemText(checkedListBox1.Items[i]);

           }

       }

}

 

 

6.

设置CheckedListBox中第i项的Checked状态
checkedListBox1.SetItemCheckState(i, CheckState.Checked);

 

 

7.
private void checkBoxAll_CheckedChanged(object sender, EventArgs e)
{
     if (checkBoxAll.Checked)
     {
         //
被选择了则将CheckedListBox中的所有条目都变为Checked状态
         for (int i = 0; i < checkedListBoxLayerControl.Items.Count;

                   i++)
         {    

checkedListBoxLayerControl.SetItemCheckState(i,

        CheckState.Checked);
}

}
else
{
     //
否则变成Unchecked状态
    for (int i = 0;

 i < checkedListBoxLayerControl.Items.Count; i++)
{

checkedListBoxLayerControl.SetItemCheckState(i, CheckState.Unchecked); 

}             

}
}


8.
checkedListBox
单选设置(代码实现)


private void chkl_ItemAuditing_ItemCheck(object sender,   

ItemCheckEventArgs e)
{
     if (chkl_ItemAuditing.CheckedItems.Count > 0)
    {
         for (int i = 0; i < chkl_ItemAuditing.Items.Count; i++)
         {

if (i != e.Index)
{
this.chkl_ItemAuditing.SetItemCheckState(i,

System.Windows.Forms.CheckState.Unchecked);
}

}
}

}

9.
checkedListBox1
显示一个数据库中关键字对应的所有记录


for (int i = 0; i < table.Rows.Count; i++)
{
    string name = table.Rows["myname"].ToString();
    string paw = table.Rows["mypaw"].ToString();
    checkedListBox1.Items.Add(name + paw);
}

 

10.
for(i=0;i<CheckedListBox.Items.Count;i++)  
{  
   if(CheckedListBox.GetItemText(

CheckedListBox.Items)=="你得到的值")  
{  
      CheckedListBox.SetItemChecked(i,true);  
}  

}

 

11.

清除checkedListBox1中所有的选项


for (int i = 0; i < checkedListBox1.Items.Count; i++)

{

    checkedListBox1.Items.Clear();

}



12.

//设置索引为index的项为选中状态


for (int i = 0; i < checkedListBox1.Items.Count; i++)

{

    checkedListBox1.SetItemChecked(i, true);

 

13.  
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{

if (checkedListBox1.GetSelected(i))

{

MessageBox.Show(checkedListBox1.CheckedItems.ToString());

}

}

 

14.

//选中checkedListBox1所有的选项

 

for (int i = 0; i < checkedListBox1.Items.Count; i++)        
{

checkedListBox1.SetItemCheckState(i, CheckState.Checked);

}

 

15.            
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{ 

//如果checkedListBox1的第i项被选中,

//则显示checkedListBox1对应的值

if (checkedListBox1.GetItemChecked(i))
{
     MessageBox.Show(checkedListBox1.Items.ToString());
}

}

 

16.

//反向选择checkedListBox1的选项


for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
    if (checkedListBox1.GetItemChecked(i))
   {
       checkedListBox1.SetItemChecked(i, false);
   }
   else
   {
       checkedListBox1.SetItemChecked(i, true);
   }
}

17.

//checkedListBox1中选定的项->checkedListBox2


for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
     checkedListBox2.Items.Add(this.checkedListBox1.CheckedItems);

 

//remove是除去一个具体的值,不是index,注意了
     this.checkedListBox1.Items.Remove(

         this.checkedListBox1.CheckedItems);      
}

Tags:

技术文章

数据库连接错误

by jack 14. July 2009 19:34

我在执行.NET应用程序时,遇到如下数据库连接错误:

A connection was successfully established with the server, but then an error occurred during the pre-login handshake. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider, error: 0 - No process is on the other end of the pipe.)

 

错误原因:

When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections.即:在连接到SQL Server 2005时,错误产生的原因可能是由SQL Server的默认设置不允许远程连接造成的。

解决方法:

确保SQL Server 2005的配置是否正确,允许传入的连接上的实例数据库服务器,否则,使对本地连接和远程连接进行设置。

  1. Click Start button, then go to Programs or All Programs, then select Microsoft SQL Server 2005 , followed by Configuration Tools .单击开始按钮,然后单击程序按钮,然后选择Microsoft SQL Server 2005项,其次是选择配置工具Click and run the SQL Server Surface Area Configuration .点击和运行 SQL Server外围应用配置器进入界面SQL Server 2005 Surface Area Configuration. On the “SQL Server 2005 Surface Area Configuration” page, click Surface Area Configuration for Services and Connections .
  2. 单击Surface Area Configuration for Services and Connections On the “SQL Server 2005 Surface Area Configuration” page, click Surface Area Configuration for Services and Connections .On the “Surface Area Configuration for Services and Connections” page, expand Database Engine tree, click Remote Connections .链接,进入Surface Area Configuration for Services and Connections-localhost界面,在界面左边的树形结构中,先单击MSSQLSERVER结点,再单击其展开的Database Engine结点,单击Remote Connection 项,界面右边将展现出相应的内容。
  3. 选中Local and remote connections 及其子项Using both TCP/IP and named pipesSelect Local and remote connections , or Local connections only which applicable only if there is no remote system tries to connect to the SQL Server, useful when you just trying to connect and authenticate with the server after installing.  
  4. Click OK button when prompted with the message saying that “Changes to Connection Settings will not take effect until you restart the Database Engine service.”单击OK按钮时,有如下提示讯息:

“Changes to Connection Settings will not take effect until you restart the Database Engine service ”,单击OK按钮,关闭提示,返回到SQL Server 2005 Surface Area Configuration界面

  1. 单击On the “Surface Area Configuration for Services and Connections” page, expand Database Engine tree, click Remote Connections .选择选择Surface Area Configuration for Services and Connections链接,进入Surface Area Configuration for Services and Connections-localhost界面,在界面左边的树形结构中,先单击MSSQLSERVER结点,再单击其展开的Database Engine结点,单击Remote Connection 项,界面右边将展现出相应的内容。                                            
  2. Click Stop button to stop the SQL Server service.点击 Stop按钮来停止MSSQLSERVER服务。
  3. Wait until the MSSQLSERVER service stops, and then click Start button to restart the MSSQLSERVER service.MSSQLSERVER服务停止之后,单击Start按钮,重新启动MSSQLSERVER服务。
  4. 单击OK按钮,退出界面,配置成功。

配置成功之后,问题得到解决!

 

除此之外,问题还有可能是web.config文件中的数据库连接串中的主机IP或数据库名及服务名错误!!此种情况应特别注意。

Tags:

Trouble Shooting | 技术文章

关于验证控件的初步理解

by jack 12. July 2009 22:43

VS2005VS2008自带的验证控件,几乎没有什么不同。唯一改善的地方是VS2008的验证控件的BackColor ForeColor BorderColor属性的设置比起VS2005来功能更强大。

在这里,我简要介绍了如何使用验证控件。

若要了解更多关于验证控件的使用与扩展,请访问以下网址,这儿有许多非常好的文章。

http://www.codeproject.com/KB/validation/

 

验证控件用于验证用户输入是否符合要求。有时系统会要求用户输入的数据需遵循一定的格式和规则,如邮政编码、电子邮件地址、电话号码以及年龄必须大于零等,这样才尽可能确保用户输入的数据的正确性和有效性。ASP.NET中验证控件提供了两种方式的验证:服务器端验证和客户端验证。当检测到浏览器允许客户端验证时,验证控件将在客户端进行验证,否则,将只能在服务器端进行验证。进行client-side/server-side检测和验证不需要开发人员进行额外的工作!

        

下面是用来验证用户输入的控件Web控件

RequiredFieldValidator

检查用户是否输入或选择了任何内容

CompareValidator

将输入控件与一个固定值或另一个输入控件进行比较。例如,它可以用在口令验证字段中。也可以用来比较输入的日期和数字。

RangeValidator

CompareValidator 非常相似, 只是它用来检查输入是否在两个值或其它输入控件的值之间。

RegularExpressionValidator

根据规则表达式检查用户输入。该过程允许进行许多种类的检查,可以用于邮政编码和电话号码等的检查。

CustomValidator

允许用户编写自己的代码以加入到验证框架中。

 

 

 
 
 
 
 
 
 
 
 
 
 
 多个验证控件可同时用于单个输入控件,以验证不同的标准。例如,要求用户输入他的年龄。您可以使用一个RangeValidator控制,以确保输入的值是在规定的范围和RequiredFieldValidator控件,以确保用户输入一个值到TextBox控件。

如果验证控件验证到用户输入的数据不符合要求,则其属性ErrorMessage的内容将显示在验证控件的位置。其内容还能显示在ValidationSummary控件中。

 

验证控件基础:

所有的验证控件均继承自基类BaseValidator,所以它们都有一系列相同的属性和方法。

例如:

ControlToValidate -用于指定验证对象。

ErrorMessage -这是将用于显示验证总结的错误消息。

IsValid -布尔值,用于指示验证控制是否有效。

Display-用于控制错误信息的显示方式。

 

RequiredFieldValidation控件

首先我们介绍RequiredFieldValidation控件的使用。显而易见,它确保用户输入了值。下面是其使用方式:

Core code:

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>*

         <asp:RequiredFieldValidator

               ID="reqvName" runat="server" ControlToValidate="txtName"

               ErrorMessage="The name can not be blank!" Display="static">

</asp:RequiredFieldValidator>

在附带的项目ValidatorControlDemo中,页面RequiredFieldValidatorDemo.aspx是其使用实例。

CompareValidator控件

接下来我们看看CompareValidator控件的使用。使用本CompareValidator控件是确认两次输入的密码是否一致。实例如下:

Core code:

         <asp:Label ID="lblRePassword" runat="server" Text="Re-enter Password:"></asp:Label>

         <asp:TextBox ID="txtRePassword" runat="server" Width="126px"></asp:TextBox>*

         <asp:CompareValidator ID="cmpvPassword" runat="server"

                   ControlToCompare="txtRePassword" ControlToValidate="txtPassword"

                   ErrorMessage="Two password the importation is inconsistent!" Display="Dynamic">

</asp:CompareValidator>

 

 

在这里,验证我们的两个文本框的内容是否相等的。这个控件中的ControlToCompare属性是CompareValidator控件所特有的,用于指定另一个比较对象。这两个控件的比较类型将由Operator属性指定。Operator属性值可为Equal GreterThan LessThanOrEqual等。


ComapareValidator
控件的另一个使用方式是同一个值进行比较。例如:

Core code:

            <asp:Label ID="lblNumber" runat="server" Text="Enter Number:"></asp:Label>

            <asp:textbox id="txtNumber" runat="server"/>

            <asp:CompareValidator id="reqvNumber" runat="server" ControlToValidate="txtNumber" ValueToCompare="50"

Type="Integer"  Operator="GreaterThan"

                 ErrorMessage="You must enter the a number greater than 50!" Display="Dynamic">

            </asp:CompareValidator>

在附带的项目ValidatorControlDemo中,页面CompareValidatorDemo.aspx是它们的使用实例。
数据类型可以是:Currency, Double, Date, Integer or StringString为默认的数据类型。

RangeValidator 控件
Range Validator
控件是另一个用于检查输入值是否在有效的范围内的验证控制。其是必要的属性是: MaximumValue MinimumValueType。例如:

Core Code:

            <asp:Label ID="lblBirthday" runat="server" Text="Birthbay:"></asp:Label>

            <asp:TextBox ID="txtBirthday" runat="server" Width="128px"></asp:TextBox>

            <asp:RangeValidator ID="rngvBirthday" runat="server" ControlToValidate="txtBirthday" Type="Date"

ErrorMessage="The birthday must be between 1/1/1990 and 12/13/2010."

                      MaximumValue="12/13/2010" MinimumValue="1/1/1900" Display="Dynamic">

</asp:RangeValidator>

在附带的项目ValidatorControlDemo中,页面RangeValidatorDemo.aspx是其使用实例。


RegularExpressionValidator控件
正则表达式验证控件是ASP.NET 中一个功能强大的验证控件。几乎每个人都会喜欢用正则表达式。其使用方法如下:

 Core Code:

            <asp:Label ID="lblEmail" runat="server" Text="Email:"></asp:Label>

            <asp:TextBox ID="txtEmail" runat="server" Width="206px"></asp:TextBox>

            <asp:RegularExpressionValidator ID="rexpEmial" runat="server"

                   ControlToValidate="txtEmail" Display="Dynamic"

ErrorMessage="Email format is not consistent with."

                   ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">

</asp:RegularExpressionValidator>

在附带的项目ValidatorControlDemo中,页面RegularExpressionValidatorDemo.aspx是其使用实例。


关于正则表达式的语法和常用的正则表达式, 请参考网址:

http://www.cnblogs.com/Caesar/archive/2008/07/30/1256486.html

 


CustomValidator控件
ASP.NET
中关于表单验证的最后一个控件是一个具有很大灵活性的验证控CustomValidator,增加了我们的验证能力。这个自定义验证控件使我们可以写出函数,并通过它验证用户输入值。其用法如下:

 Core Code:

        <asp:Label ID="lblLuckyNumber" runat="server" Text="Your Lucky Number:"></asp:Label>

        <asp:TextBox ID="txtLuckyNumber" runat="server" Width="126px"></asp:TextBox>

        <asp:CustomValidator ID="custvLuckyNumber" runat="server"

               ControlToValidate="txtLuckyNumber" ErrorMessage="Lucky number must be even!"

               OnServerValidate="ServerValidation" Display="Dynamic">

</asp:CustomValidator>

在附带的项目ValidatorControlDemo中,页面CustomValidatorDemo.aspx是其使用实例。


关于CustomValidator控件更详细的信息, 下面这个网址有更详细的信息:

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx


Validation Summary控件
ASP.NET
有提供了一个额外的控件ValidationSummary,用于集中显示不符合要求的用户输入消息。其使用方法如下:

 Core Code:      

<asp:ValidationSummary ID="vsumErrors" runat="server"

                  HeaderText="Errors:" DisplayMode="BulletList"/>

在附带的项目ValidatorControlDemo中,页面ValidationSummaryDemo.aspx

是其使用实例。


ValidationSummary
控件将收集所有不符合要求的验证控件的Error Messages的值并将其放入一个列表中。该清单显示在网页上或弹出框(通过指定属性ShowMessageBox = True” )

ValidatorContorlDemo.rar (32.73 kb)

Tags:

技术文章

Copyright © 2009 APJ Software

最新评论

Comment RSS

公告

欢迎使用APJ Blog!

日历

<<  May 2012  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar