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

来源:http://www.cnblogs.com/geovindu/archive/2016/08/06/5745181.html
-Advertisement-
Play Games

stdafx.h: Form1.h ...


stdafx.h:

// 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

 

#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);
		 }
};
}

  


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.把資料庫裡面的數據顯示出來 sqlHelper怎麼用:[網上可以下載,需要可以找樓主要] 1.拷貝到項目,修改它的命名空間等於當前項目名稱 2.資料庫的連接信息,用戶名,密碼,登錄方式等 <connectionStrings> <add name="con" connectionString=" ...
  • 第一次寫博客,不知道代碼用什麼編輯,直接截圖了,哈哈哈。。。。 我自己不喜歡看隨便複製粘貼過來一堆代碼的博客,所以,用些簡單點的例子吧,希望對大家有幫助。。。 一 、自動屬性。 1、vs下輸入prop,Tab鍵就出現了。 2、有了自動屬性,我們不用再額外為一個類的每個公共屬性定義一個私有欄位(實際上 ...
  • 重載的條件: 1.必須在同一個類中2.方法名必須相同3.參數列表不能相同。 重寫的條件: 1. 在不同的類中 2. 發生方法重寫的兩個方法返回值,方法名,參數列表必須完全一致 3. 子類拋出的異常不能超過父類相應的方法拋出的異常 4. 子類方法的訪問級別不能低於父類相應方法的訪問級別(public, ...
  • 前言:以前總說自己玩mvc,但是對mvc的認識還是不夠透徹,也沒有好好看微軟自帶的mvc項目中的精妙,最近閑了下來,好好看了看。 通過上圖,我們可以清晰地瞭解到MVC 5應用程式的項目結構,接下來我們來依次解釋下他們各自的應用。 App_Data: 該文件夾主要是包含應用程式的本地存儲, 它通常以文 ...
  • 在hibernate中我們知道如果要從資料庫中得到一個對象,通常有兩種方式,一種是通過session.get()方法,另一種就是通過session.load()方法,然後其實這兩種方法在獲得一個實體對象時是有區別的,在查詢性能上兩者是不同的。 一.load載入方式 當使用load方法來得到一個對象時 ...
  • 持久化(Persistence) 即把數據(如記憶體中的對象)保存到可永久保存的存儲設備中(如磁碟)。持久化的主要應用是將記憶體中的對象存儲在關係型的資料庫中,當然也可以存儲在磁碟文件中、XML數據文件中等等。 持久化是將程式數據在持久狀態和瞬時狀態間轉換的機制。 JDBC就是一種持久化機制。文件IO也 ...
  • //fourth day to study python 24. In python , how to create funcation. we can use def to define funcation. such as: def MyFirstFuncation(): print('this ...
  • 請註意以下要點: 1、是否開啟了認證,QQ郵箱、163郵箱均要開啟認證 2、javax.mail.MessagingException: Could not connect to SMTP host: smtp.163.com, port: 25; //連接超時 解決參考:將這個屬性的true加上引 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...