C + +: Read SQL Server data using System::D ata::sqlclient

Source: Internet
Author: User

StdAfx.h:

Stdafx.h:include file for standard system include files,//or project specific include files, is used frequently , but//is 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 oncenamespace sqlserver2008r2inccli {using namespace system;using namespace system::componentmodel;using Namespace system::collections;using namespace system::windows::forms;using namespace System::D ata;using namespace    System::D rawing;using namespace System::configuration; Using namespace Adodb;//c:\program Files\Common Files\system\ado\msado15.dllusing namespace System::D ata::sqlclient ;///<summary>///Summary for form1//////Warning:if. The name of this class, you'll need to change the ' Resource File Name ' property for the managed Resource compiler tool///associated with all. resx fi  Les this class depends on.  otherwise,///The designers is not being 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 No resources being used.///</summary>~form1 () {if (components) {delete components;}}        Private:system::windows::forms::D atagridview^ 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 no 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::D atagridview ());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::D atagridviewcolumnheadersheightsizemode::autosize;this->datagridview1->location = System: :D rawing::P oint (), this->datagridview1->name = L "DataGridView1";this->datagridview1-> Showcelltooltips = False;this->datagridview1->size = System::D rawing::size (493, 266); this->datagridview1->tabindex = 0;this->datagridview1->mousedown + = gcnew system::windows::forms:: MouseEventHandler (This, &form1::d atagridview1_mousedown); This->datagridview1->dataerror + = gcnew System: : windows::forms::D Atagridviewdataerroreventhandler (This, &form1::d atagridview1_dataerror);///label1//this- >label1->location = System::D rawing::P oint (9); this->label1->name = L "Label1";this->label1-> Size = System::D rawing::size (+), This->label1->tabindex = 1;this->label1->text = L "Select Table to show: ";///comboboxtables//This->comboboxtables->dropdownstyle = System::windows::forms::comboboxstyle::D ropdownlist;this->comboboxtables->formattingenabled = True;this->comboboxtables->location = System::D Rawing::P oint, this->comboboxtables->name = L "Comboboxtables"; this->comboboxtables->size = System::D rawing::size (165); This->comboboxtables->tabindex = 2;////buttonok//THIS-&GT;buttonok->location = System::D rawing::P oint (254, n); this->buttonok->name = L "Buttonok";this-> Buttonok->size = System::D rawing::size (up to), 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::D Rawing::sizef (6,;this->) AutoScaleMode = System::windows::forms::autoscalemode::font;this->clientsize = System::D rawing::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 endregionstring ^servername, ^dbname;        SqlConnection ^conn;        SqlDataAdapter ^adapter; DataTable ^dtmain;private:system::void Form1_Load (system::object^ sender, system::eventargs^ e) {ServerName = "geovind             U-pc\\geovin ";             DBName = "Duvehicle"; Create database if not EXISTS//try {//adodb::connection= "";//c:\program Files\Common Files\system\ado\msa Do15.dll//Connect to Server//to the database "master" to the check if our database existS//To create it if it isn ' t exists//conn = gcnew SqlConnection ("server=" + ServerName + ";D atab Ase=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 (PRIMARY KEY CLUSTERED), "+// "[Text column] [text] null," +//"[int column] [int] NULL"     +//")",//"Table 1"), conn); Cmd->executenonquery ();             Delete cmd; conn = gcnew SqlConnection ("server=" + ServerName + ";D atabase=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 Cellprivate:system::void D Atagridview1_dataerror (system::object^ sender, System::wiNdows::forms::D atagridviewdataerroreventargs^ 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 was for numbers only."; Tooltip1->show ("", DataGridView1, Rectcolumn->left, rectrow->t            OP + rectrow->height);d elete rectcolumn;delete Rectrow; }}private:system::void Datagridview1_mousedown (system::object^ sender, system::windows::forms::mouseeventargs^ e) { Tooltip1->hide (DATAGRIDVIEW1); }};}

  

C + +: Read SQL Server data using System::D ata::sqlclient

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.