C++: read SQL server data using System::Data::SqlClient

stdafx.h:

1
2
3
4
5
6
7
8
9
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
#pragma once
#using <mscorlib.dll>
#using <System.dll>
#using <System.Data.dll>
#using <System.Xml.dll>
// TODO: reference additional headers your program requires here

  Form1.h

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
#pragma once
 
 
namespace SQLServer2008R2inCCLI {
 
    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;
    using namespace System::Configuration;
    using namespace ADODB;//c:\Program Files\Common Files\System\ADO\msado15.dll
 
    using namespace System::Data::SqlClient;
 
    /// <summary>
    /// Summary for Form1
    ///
    /// WARNING: If you change the name of this class, you will need to change the
    ///          'Resource File Name' property for the managed resource compiler tool
    ///          associated with all .resx files this class depends on.  Otherwise,
    ///          the designers will not be able to interact properly with localized
    ///          resources associated with this form.
    /// </summary>
    public ref class Form1 : public System::Windows::Forms::Form
    {
    public:
        Form1(void)
        {
            InitializeComponent();
            //
            //TODO: Add the constructor code here
            //
        }
 
    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~Form1()
        {
            if (components)
            {
                delete components;
            }
        }
            private: System::Windows::Forms::DataGridView^ dataGridView1;
        private: System::Windows::Forms::Label^ label1;
        private: System::Windows::Forms::ComboBox^ comboBoxTables;
        private: System::Windows::Forms::Button^ buttonOK;
        private: System::Windows::Forms::ToolTip^ toolTip1;
    private: System::ComponentModel::IContainer^  components;
    protected:
 
    private:
        /// <summary>
        /// Required designer variable.
        /// </summary>
 
 
#pragma region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        void InitializeComponent(void)
        {
            this->components = (gcnew System::ComponentModel::Container());
            this->dataGridView1 = (gcnew System::Windows::Forms::DataGridView());
            this->label1 = (gcnew System::Windows::Forms::Label());
            this->comboBoxTables = (gcnew System::Windows::Forms::ComboBox());
            this->buttonOK = (gcnew System::Windows::Forms::Button());
            this->toolTip1 = (gcnew System::Windows::Forms::ToolTip(this->components));
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->dataGridView1))->BeginInit();
            this->SuspendLayout();
            //
            // dataGridView1
            //
            this->dataGridView1->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom)
                | System::Windows::Forms::AnchorStyles::Left)
                | System::Windows::Forms::AnchorStyles::Right));
            this->dataGridView1->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize;
            this->dataGridView1->Location = System::Drawing::Point(12, 44);
            this->dataGridView1->Name = L"dataGridView1";
            this->dataGridView1->ShowCellToolTips = false;
            this->dataGridView1->Size = System::Drawing::Size(493, 266);
            this->dataGridView1->TabIndex = 0;
            this->dataGridView1->MouseDown += gcnew System::Windows::Forms::MouseEventHandler(this, &Form1::dataGridView1_MouseDown);
            this->dataGridView1->DataError += gcnew System::Windows::Forms::DataGridViewDataErrorEventHandler(this, &Form1::dataGridView1_DataError);
            //
            // label1
            //
            this->label1->Location = System::Drawing::Point(12, 9);
            this->label1->Name = L"label1";
            this->label1->Size = System::Drawing::Size(65, 32);
            this->label1->TabIndex = 1;
            this->label1->Text = L"Select table to show:";
            //
            // comboBoxTables
            //
            this->comboBoxTables->DropDownStyle = System::Windows::Forms::ComboBoxStyle::DropDownList;
            this->comboBoxTables->FormattingEnabled = true;
            this->comboBoxTables->Location = System::Drawing::Point(83, 12);
            this->comboBoxTables->Name = L"comboBoxTables";
            this->comboBoxTables->Size = System::Drawing::Size(165, 21);
            this->comboBoxTables->TabIndex = 2;
            //
            // buttonOK
            //
            this->buttonOK->Location = System::Drawing::Point(254, 12);
            this->buttonOK->Name = L"buttonOK";
            this->buttonOK->Size = System::Drawing::Size(56, 21);
            this->buttonOK->TabIndex = 3;
            this->buttonOK->Text = L"OK";
            this->buttonOK->UseVisualStyleBackColor = true;
            this->buttonOK->Click += gcnew System::EventHandler(this, &Form1::buttonOK_Click);
            //
            // toolTip1
            //
            this->toolTip1->AutoPopDelay = 5000;
            this->toolTip1->InitialDelay = 0;
            this->toolTip1->IsBalloon = true;
            this->toolTip1->ReshowDelay = 0;
            this->toolTip1->ToolTipIcon = System::Windows::Forms::ToolTipIcon::Warning;
            this->toolTip1->UseAnimation = false;
            this->toolTip1->UseFading = false;
            //
            // Form1
            //
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(517, 322);
            this->Controls->Add(this->buttonOK);
            this->Controls->Add(this->comboBoxTables);
            this->Controls->Add(this->label1);
            this->Controls->Add(this->dataGridView1);
            this->Name = L"Form1";
            this->Text = L"Form1";
            this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
            this->FormClosed += gcnew System::Windows::Forms::FormClosedEventHandler(this, &Form1::Form1_FormClosed);
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  >(this->dataGridView1))->EndInit();
            this->ResumeLayout(false);
 
        }
#pragma endregion
        String ^ServerName, ^DBName;
 
        SqlConnection ^conn;
        SqlDataAdapter ^adapter;
        DataTable ^dtMain;
 
    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
                 ServerName = "GEOVINDU-PC\\GEOVIN";
                 DBName = "DuVehicle";
 
 
 
                 // create database if not exists
                 //try {
                    // ADODB::Connection="";//c:\Program Files\Common Files\System\ADO\msado15.dll
 
                                     // connect to server
                 // to database "master" to check if our database exists
                 // to create it if it isn't exists
                 //conn = gcnew SqlConnection("Server=" + ServerName + ";Database=DuVehicle;UID=sa;PWD=geovindu;");
                 //conn->Open();
                     //SqlCommand ^cmd = gcnew SqlCommand(String::Format("CREATE DATABASE [{0}] ON (" +
      //                                              "    NAME = {0}, " +
                        //                          "    FILENAME = '" + Application::StartupPath + "\\{0}.mdf'" +
      //                                              ");",
      //                                              DBName), conn);
      //               cmd->ExecuteNonQuery();
                     //delete cmd;
                /* }
                 catch (Exception ^ex) { }*/
 
 
                 // create table "Table 1" if not exists
                 //SqlCommand ^cmd = gcnew SqlCommand(String::Format(
     //                                 "IF NOT EXISTS (" +
     //                                 "    SELECT [name] " +
     //                                 "    FROM sys.tables " +
     //                                 "    WHERE [name] = '{0}'" +
     //                                 ") " +
     //                                 "CREATE TABLE [{0}] (" +
     //                                 "    id [INT] IDENTITY(1,1) PRIMARY KEY CLUSTERED, " +
     //                                 "    [text column] [TEXT] NULL, " +
     //                                 "    [int column] [INT] NULL " +
     //                                 ")",
     //                                 "Table 1"), conn);
     //          cmd->ExecuteNonQuery();
                 //delete cmd;
                 conn = gcnew SqlConnection("Server=" + ServerName + ";Database=DuVehicle;UID=sa;PWD=geovindu;");
                 conn->Open();
                 // get all tables from DB
                 DataTable ^dt = conn->GetSchema("Tables");
                 for (int i = 0; i < dt->Rows->Count; i++) {
                    if (dt->Rows[i]->ItemArray[dt->Columns->IndexOf("TABLE_TYPE")]->ToString() == "BASE TABLE") {
                        comboBoxTables->Items->Add(dt->Rows[i]->ItemArray[dt->Columns->IndexOf("TABLE_NAME")]->ToString());
                    }
                 }
                 delete dt;
             }
private: System::Void buttonOK_Click(System::Object^  sender, System::EventArgs^  e) {
             if (comboBoxTables->SelectedItem == nullptr) return;
 
             adapter = gcnew SqlDataAdapter("SELECT * FROM [" + comboBoxTables->SelectedItem->ToString() + "]", conn);
 
             gcnew SqlCommandBuilder(adapter);
 
             dtMain = gcnew DataTable();
             adapter->Fill(dtMain);
             dtMain->Columns["id"]->ReadOnly = true; // deprecate id field edit to prevent exceptions
             dataGridView1->DataSource = dtMain;
         }
private: System::Void Form1_FormClosed(System::Object^  sender, System::Windows::Forms::FormClosedEventArgs^  e) {
             if (adapter == nullptr) return;
 
             adapter->Update(dtMain);
         }
         // show tooltip (not intrusive MessageBox) when user trying to input letters into INT column cell
private: System::Void dataGridView1_DataError(System::Object^  sender, System::Windows::Forms::DataGridViewDataErrorEventArgs^  e) {
             if (dtMain->Columns[e->ColumnIndex]->DataType == Int64::typeid ||
                 dtMain->Columns[e->ColumnIndex]->DataType == Int32::typeid ||
                dtMain->Columns[e->ColumnIndex]->DataType == Int16::typeid)
            {
                Rectangle ^rectColumn;
                rectColumn = dataGridView1->GetColumnDisplayRectangle(e->ColumnIndex, false);
 
                Rectangle ^rectRow;
                rectRow = dataGridView1->GetRowDisplayRectangle(e->RowIndex, false);
 
                toolTip1->ToolTipTitle = "This field is for numbers only.";
                toolTip1->Show(" ",
                          dataGridView1,
                          rectColumn->Left, rectRow->Top + rectRow->Height);
 
                delete rectColumn;
                delete rectRow;
            }
         }
private: System::Void dataGridView1_MouseDown(System::Object^  sender, System::Windows::Forms::MouseEventArgs^  e) {
             toolTip1->Hide(dataGridView1);
         }
};
}

  

posted @   ®Geovin Du Dream Park™  阅读(653)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2014-08-06 csharp:qq weather
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示