Использовать открытый статический класс и получить доступ к нему из любого места.
public static class MyGlobals {
public const string Prefix = "ID_"; // cannot change
public static int Total = 5; // can change because not const
}
используется так: от главной страницы или где угодно:
string strStuff = MyGlobals.Prefix + "something";
textBox1.Text = "total of " + MyGlobals.Total.ToString();
Вам не нужно создавать экземпляр класса; на самом деле вы не можете, потому что это статично. new
Просто используйте его напрямую. Все члены внутри статического класса также должны быть статическими. Строка Prefix не помечена как статическая, поскольку const
неявно статична по своей природе.
Статический класс может быть в любом месте вашего проекта. Он не должен быть частью Global.asax или какой-либо конкретной страницы, потому что он «глобальный» (или, по крайней мере, как можно ближе к этой концепции в объектно-ориентированных терминах.)
Вы можете сделайте столько статических классов, сколько захотите, и назовите их, как хотите.
Иногда программисты любят группировать свои константы с помощью вложенных статических классов. Например,
public static class Globals {
public static class DbProcedures {
public const string Sp_Get_Addresses = "dbo.[Get_Addresses]";
public const string Sp_Get_Names = "dbo.[Get_First_Names]";
}
public static class Commands {
public const string Go = "go";
public const string SubmitPage = "submit_now";
}
}
и получить к ним доступ так:
MyDbCommand proc = new MyDbCommand( Globals.DbProcedures.Sp_Get_Addresses );
proc.Execute();
//or
string strCommand = Globals.Commands.Go;
Я бы предложил добавить класс и затем наследовать элемент управления DataGridView в этом классе. Я сделал небольшой небольшой пример этого, и код работает, но чтобы заставить его работать, вам нужно будет выполнить несколько шагов:
(1) Если у вас еще нет приложения Windows Form для Затем проверьте это, сделайте новый. (2) Создайте класс с именем KeyedDataGridView
(3) Скопируйте и вставьте следующий код в класс KeyedDataGridView
(4) Перестройте свой проект
(5) Перетащите и отпустите новый компонент на форму Windows.
ПРИМЕЧАНИЕ. Этот класс ограничен, но он все еще должен выполнять то, что вам требуется.
Наконец, если вам нужна помощь, пожалуйста, оставьте комментарий и постараюсь добраться до него, когда смогу.
Option Explicit On
Public Class KeyedDataGridView
Inherits Windows.Forms.DataGridView
Dim _Rows As KeyedDataRows
Public Shadows Property Rows As KeyedDataRows
Get
Return _Rows
End Get
Set(value As KeyedDataRows)
_Rows = value
End Set
End Property
Public Sub New()
Dim strName As String
strName = Me.Name
strName = MyBase.Name
_Rows = New KeyedDataRows(Me)
_Rows.Rows = MyBase.Rows
End Sub
Protected Overrides Sub Finalize()
_Rows = Nothing
MyBase.Finalize()
End Sub
End Class
Public Class KeyedDataRows
Inherits Windows.Forms.DataGridViewRowCollection
Dim _TagNames As Dictionary(Of String, Integer)
Dim _Rows As DataGridViewRowCollection
Dim _Cells As Dictionary(Of String, DataGridViewCellCollection)
Dim dgv As DataGridView
Default Public Overloads ReadOnly Property Item(strTagName As String) As DataGridViewRow
Get
Return _Rows.Item(Me.IndexFromName(strTagName))
End Get
End Property
Protected Friend Property Rows As DataGridViewRowCollection
Get
Return _Rows
End Get
Set(value As DataGridViewRowCollection)
_Rows = value
End Set
End Property
Public Property TagName(index As Integer) As String
Get
Return CStr(_TagNames.Item(index))
End Get
Set(value As String)
_TagNames.Item(index) = value
End Set
End Property
Public Sub New(tmp As DataGridView)
MyBase.New(tmp)
dgv = tmp
_TagNames = New Dictionary(Of String, Integer)
_Cells = New Dictionary(Of String, DataGridViewCellCollection)
End Sub
Public Shadows Sub Add(strTagName As String)
Dim intCurRow As Integer
If dgv.AllowUserToAddRows Then
intCurRow = _Rows.Count - 1
Else
intCurRow = _Rows.Count
End If
_TagNames.Add(strTagName, intCurRow)
_Rows.Add()
End Sub
Public Shadows Sub Add(strTagName As String, dataGridViewRow As DataGridViewRow)
Dim intCurRow As Integer
If dgv.AllowUserToAddRows Then
intCurRow = _Rows.Count - 1
Else
intCurRow = _Rows.Count
End If
_TagNames.Add(strTagName, intCurRow)
_Rows.Add(dataGridViewRow)
End Sub
Public Shadows Sub Add(count As Integer, strTagNames() As String)
Dim intI As Integer
Dim intCurRow As Integer
If dgv.AllowUserToAddRows Then
intCurRow = _Rows.Count - 1
Else
intCurRow = _Rows.Count
End If
For intI = 0 To (count - 1)
_TagNames.Add(strTagNames(intI), intCurRow)
_Rows.Add()
intCurRow = _Rows.Count - 1
Next intI
End Sub
Public Property IndexFromName(strTagName As String) As Integer
Get
If _TagNames.Count > 0 Then
If _TagNames.ContainsKey(strTagName) Then
Return _TagNames.Item(strTagName)
Else
Return -1
End If
Else
Return -1
End If
End Get
Set(value As Integer)
_TagNames.Add(strTagName, value)
End Set
End Property
Public Overloads Sub RemoveAt(strTagName As String)
_Cells.Remove(strTagName)
_Rows.RemoveAt(IndexFromName(strTagName))
_TagNames.Remove(strTagName)
End Sub
Protected Overrides Sub Finalize()
_TagNames.Clear()
_TagNames = Nothing
_Cells.Clear()
_Rows.Clear()
_Cells = Nothing
_Rows = Nothing
MyBase.Finalize()
End Sub
End Class
Я также добавил следующие кнопки в форму окна для проверки кода:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
With KeyedDataGridView1
.Rows.Add("Tag Test 1")
.Rows.Add("Tag Test 2")
.Rows.Add("Tag Test 3")
.Rows.Add("Tag Test 4")
End With
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
MsgBox(KeyedDataGridView1.Rows("Tag Test 3").Cells(0).Value & vbCrLf &
KeyedDataGridView1.Rows("Tag Test 3").Cells(1).Value & vbCrLf &
KeyedDataGridView1.Rows("Tag Test 3").Cells(2).Value)
MsgBox(KeyedDataGridView1.Rows("Tag Test 2").Cells(0).Value & vbCrLf &
KeyedDataGridView1.Rows("Tag Test 2").Cells(1).Value & vbCrLf &
KeyedDataGridView1.Rows("Tag Test 2").Cells(2).Value)
MsgBox(KeyedDataGridView1.Rows("Tag Test 1").Cells(0).Value & vbCrLf &
KeyedDataGridView1.Rows("Tag Test 1").Cells(1).Value & vbCrLf &
KeyedDataGridView1.Rows("Tag Test 1").Cells(2).Value)
End Sub