简体   繁体   English

如何在C#中以所有形式提供字符串

[英]How to make a string available in all the forms in C#

I'm using Compact Framework 2.0 for an application in Windows CE 5.0 device with multiple forms. 我将Compact Framework 2.0用于具有多种形式的Windows CE 5.0设备中的应用程序。

I have to use a connection string in almost all the forms in order to access to the database: 我必须以几乎所有形式使用连接字符串才能访问数据库:

string conString = "Data Source=\\Program Files\\myproject\\database.sdf";

I would like to know if it's possible to make this connection string somehow "global" in order to be written only once and accessible from all the forms. 我想知道是否有可能使此连接字符串以某种方式成为“全局”,以便仅编写一次并可以从所有形式访问。

As per @Steven's comment, you should really add this in the config file, however see below for an example of what you asked for. 根据@Steven的评论,您应该将其确实添加到配置文件中,但是请参阅以下示例以了解所需内容。

Create a class for it and make it a public const field. 为此创建一个类,并将其设置为公共const字段。

public static class Globals
{
    public const string conString = "Data Source=\\Program Files\\myproject\\database.sdf"; 
}

Then in your forms (or anywhere else) you could access it as Globals.conString . 然后,在您的表单(或其他任何地方)中,您可以作为Globals.conString访问它。

For more flexibility you can use readonly keyword. 为了获得更大的灵活性,您可以使用readonly关键字。 Readonly members are initilized at runtime and can hold complex objects. 只读成员在运行时初始化,并且可以容纳复杂的对象。

public class DataBaseConfiguration
{
     public readonly String conStr;

     public DataBaseConfiguration(String conString)
     {
          this.conString = conString;
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 一个mysql连接可用于C#中的所有表单 - One mysql connection available for all forms in C# 如何以C#Win形式从MySQL获取所有可用数据库到comboBox控件中 - How to fetch all available databases from MySQL into comboBox control in C# win forms 如何使KeyPress事件处理程序可用于所有表单? - How do I make KeyPress event handler available to all forms? 如何使 static class 中的所有方法在另一个 static 中可用 class 在 c# 中 - How to make all methods from static class available in another static class in c# 我如何创建一个字符串数组并使其可用于我们的 C# 控制台应用程序中的所有方法 - How i can create an array of strings and make it available to all the method inside our C# console application 如何在所有 forms 上使用创建的实例/如何使我的实例公开 C# windowsforms - How to use created Instance on all forms / How to make my instance public C# windowsforms 如何将 C# 类作为字符串 UserInput,并使其可用于 ASP.NET Core 运行时? - How can I take a C# Class, as a string UserInput, and make it available to the ASP.NET Core runtime? 如何在C#Windows Forms的类中制作连接字符串和sql helper命令 - How to make a connection string and sql helper command in class on c# windows forms C#关闭所有表格 - C# close all forms 如何使.dll可用于C#和Excel VBA - How to make .dll available for C# and Excel VBA
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM