| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786 |
- /*******************************************************************************
- * Copyright(c) 2012 dongke All rights reserved. / Confidential
- * 类的信息:
- * 1.程序名称:dkDataGridView.cs
- * 2.功能描述:扩展的DataGridView控件
- * 编辑履历:
- * 作者 日期 版本 修改内容
- * 欧阳涛 2012/06/07 1.00 新建
- * 周兴 2012/07/24 1.00 扩展复合型表头和树形结构
- *******************************************************************************/
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Diagnostics;
- using System.Drawing;
- using System.Windows.Forms;
- using System.Windows.Forms.VisualStyles;
- using Dongke.IBOSS.Framework.DKResources;
- using Dongke.IBOSS.Framework.Library;
- namespace Dongke.IBOSS.Framework.Controls
- {
- /// <summary>
- /// 剪贴板的种类枚举
- /// </summary>
- public enum ClipboardType
- {
- InnerAndDisp,
- InnerOnly
- }
- /// <summary>
- /// 过滤类型
- /// </summary>
- public enum FilterType
- {
- /// <summary>
- /// 全部匹配
- /// </summary>
- Equal,
- /// <summary>
- /// 全部不匹配
- /// </summary>
- NotEqual,
- /// <summary>
- /// 模糊匹配
- /// </summary>
- Like,
- /// <summary>
- /// 不模糊匹配
- /// </summary>
- NotLike
- }
- public partial class dkDataGridView : DataGridView
- {
- #region 枚举类型
- /// <summary>
- /// CELL的背景色区分
- /// </summary>
- [Flags]
- public enum CellBackColorFlags
- {
- /// <summary>
- /// 无背景色
- /// </summary>
- None = 0,
- /// <summary>
- /// 只读背景色
- /// </summary>
- ReadOnlyBackColor = 1,
- /// <summary>
- /// 内容有变化的背景色
- /// </summary>
- ChangesBackColor = 2,
- /// <summary>
- /// 所有全部背景色
- /// </summary>
- All = ReadOnlyBackColor | ChangesBackColor
- }
- /// <summary>
- /// 右键菜单选项
- /// </summary>
- [Flags]
- public enum ContextMenuVisibleFlags
- {
- /// <summary>
- /// 无
- /// </summary>
- None = 0,
- /// <summary>
- /// 过滤
- /// </summary>
- Refine = 1,
- /// <summary>
- /// 输出Excel文件
- /// </summary>
- FileOut = 2,
- /// <summary>
- /// 打印
- /// </summary>
- Print = 3,
- /// <summary>
- /// 所有菜单
- /// </summary>
- All = Refine | FileOut
- }
- #endregion
- #region 委托
- public delegate void CsvConveringEventHandler(object sender, CsvConvertingEventArgs e);
- #endregion
- #region 事件
- public event CsvConveringEventHandler CsvConverting = null;
- public event EventHandler MouseClickOnSpace;
- public event EventHandler RowsHeaderClick;
- #endregion
- #region 成员变量
- private ContextMenuStrip _ctxColumnHeader;
- private ContextMenuStrip _ctxCell;
- private ToolStripMenuItem _mnuFrozen = new ToolStripMenuItem();
- private ToolStripRefine _mnuRefine = new ToolStripRefine(); // 条件过滤
- private ToolStripMenuItem _mnuFilter = new ToolStripMenuItem(); // 过滤
- private ToolStripMenuItem _mnuFilterExcept = new ToolStripMenuItem(); // 除外过滤
- private ToolStripMenuItem _mnuUnfilter = new ToolStripMenuItem(); // 清除过滤
- private ToolStripMenuItem _mnuOutputFile = new ToolStripMenuItem(); // 输出csv
- private ToolStripMenuItem _mnuOutputFileXls = new ToolStripMenuItem(); // 输出excel
- private ToolStripMenuItem _mnuPrint = new ToolStripMenuItem(); // 打印
- private ToolStripMenuItem _mnuDelete = new ToolStripMenuItem(); // 删除
- private ContextMenuVisibleFlags _contextMenuVisibleFlag = ContextMenuVisibleFlags.All;
- private Label labelHideFocus; // 取得焦点的Lable
- private System.ComponentModel.IContainer components;
- private bool _isAllowUserToModifyRows = true;
- private bool _isAllowUserToSortRows = true;
- private CellBackColorFlags _cellBackColorFlag = CellBackColorFlags.None; // 背景颜色的设定标识
- private Color _cellBackColorNochanged = Color.FromArgb(255, 255, 255); // 无变化时Cell的背景颜色
- private Color _cellBackColorReadOnly = SystemColors.Control; // 只读时Cell的背景颜色
- private Color _cellBackColorAdded = Color.FromArgb(255, 230, 230); // 新建时Cell的背景颜色
- private Color _cellBackColorModified = Color.FromArgb(210, 220, 255); // 编辑时Cell的背景颜色
- private Color _cellBackColorDeleted = Color.FromArgb(240, 255, 220); // 删除时Cell的背景颜色
- private bool _isDispRowCount = true; // 是否显示总行数信息
- private int[] _selectCellRowCol = { 0, 0 }; // 选择行的行号和列号
- private bool _isFrozen = false; // 冻结·解冻标识
- private bool _isChildDGV = false;
- private string _viewRowFilterString = string.Empty;
- private string _sortOrderColumnName;
- private string _sortColumnName = string.Empty;
- private SortOrder _sortOrderType = SortOrder.None;
- private bool _isClearSelected = false;
- private bool _isShowDelete = false;
- private bool _isCanDelete = false;
- private int _gridRowIndex = 0;
- private int _gridColumnindex = 0;
- private TreeView[] _columnTreeView;
- private ArrayList _columnList = new ArrayList();
- private int _cellHeight = 25;
- private bool _hscrollRefresh = false;
- private int _columnDeep = 1;
- private TreeGridNode _root;
- private TreeGridColumn _expandableColumn;
- internal ImageList _imageList;
- private bool _virtualNodes = false;
- private bool _isHasNode = false;
- private string _nodeColumnName = string.Empty;
- private bool _inExpandCollapse = false;
- internal bool _inExpandCollapseMouseCapture = false;
- private Control hideScrollBarControl;
- private bool _showLines = true;
- private string _dynamicColumnName = string.Empty;
- private string[] _childNodeColumnName = null;
- private string[] _childNodeColumnText = null;
- private DataTable dt;//绑定的表
- private string filter = "";//filter字符串
- public bool _isOpenTotalRow = false;
- private DataGridViewColumnInfo[] _columnInfos = null;
- #endregion
- #region 公开属性
- [System.ComponentModel.Browsable(true)]
- [System.ComponentModel.DefaultValue(false)]
- [System.ComponentModel.Description("常选择。")]
- public bool IsClearSelected
- {
- get
- {
- return _isClearSelected;
- }
- set
- {
- _isClearSelected = value;
- }
- }
- [System.ComponentModel.DefaultValue(false)]
- [System.ComponentModel.Description("删除标识。")]
- public bool IsShowDelete
- {
- get
- {
- return _isShowDelete;
- }
- set
- {
- _isShowDelete = value;
- }
- }
- [System.ComponentModel.DefaultValue(false)]
- [System.ComponentModel.Description("允许删除标识。")]
- public bool IsCanDelete
- {
- get
- {
- return _isCanDelete;
- }
- set
- {
- _isCanDelete = value;
- }
- }
- [System.ComponentModel.Browsable(true)]
- [System.ComponentModel.DefaultValue(false)]
- [System.ComponentModel.Description("设定或者获取可否允许用户编辑行。")]
- public bool AllowUserToModifyRows
- {
- get
- {
- return _isAllowUserToModifyRows;
- }
- set
- {
- _isAllowUserToModifyRows = value;
- }
- }
- [System.ComponentModel.Browsable(true)]
- [System.ComponentModel.DefaultValue(true)]
- [System.ComponentModel.Description("设定或者获取可否允许用户排序。")]
- public bool AllowUserToSortRows
- {
- get
- {
- return _isAllowUserToSortRows;
- }
- set
- {
- _isAllowUserToSortRows = value;
- foreach (DataGridViewColumn column in this.Columns)
- {
- column.SortMode =
- (_isAllowUserToSortRows) ? DataGridViewColumnSortMode.Automatic :
- DataGridViewColumnSortMode.NotSortable;
- }
- }
- }
- [System.ComponentModel.Browsable(true)]
- [System.ComponentModel.DefaultValue("")]
- [System.ComponentModel.Description("设定或者获取排序的列名。")]
- public string SortOrderColumnName
- {
- get
- {
- return _sortOrderColumnName;
- }
- set
- {
- _sortOrderColumnName = value;
- }
- }
- [System.ComponentModel.Browsable(true)]
- [System.ComponentModel.DefaultValue(CellBackColorFlags.None)]
- [System.ComponentModel.Description("设定或者获取Cell背景色设定标识。")]
- public CellBackColorFlags CellBackColorFlag
- {
- get
- {
- return _cellBackColorFlag;
- }
- set
- {
- _cellBackColorFlag = value;
- }
- }
- [System.ComponentModel.Browsable(true)]
- [System.ComponentModel.DefaultValue(typeof(Color), "255, 255, 255")]
- [System.ComponentModel.Description("设定或者获取Cell没有改变时的背景颜色。")]
- public Color CellBackColorNochanged
- {
- get
- {
- return _cellBackColorNochanged;
- }
- set
- {
- _cellBackColorNochanged = value;
- }
- }
- [System.ComponentModel.Browsable(true)]
- [System.ComponentModel.DefaultValue(typeof(Color), "SystemColors.Control")]
- [System.ComponentModel.Description("设定或者获取只读Cell的背景颜色。")]
- public Color CellBackColorReadOnly
- {
- get
- {
- return _cellBackColorReadOnly;
- }
- set
- {
- _cellBackColorReadOnly = value;
- }
- }
- [System.ComponentModel.Browsable(true)]
- [System.ComponentModel.DefaultValue(typeof(Color), "255, 230, 230")]
- [System.ComponentModel.Description("设定或者获取新建Cell的背景颜色。")]
- public Color CellBackColorAdded
- {
- get
- {
- return _cellBackColorAdded;
- }
- set
- {
- _cellBackColorAdded = value;
- }
- }
- [System.ComponentModel.Browsable(true)]
- [System.ComponentModel.DefaultValue(typeof(Color), "210, 220, 255")]
- [System.ComponentModel.Description("设定或者获取编辑过Cell的背景颜色。")]
- public Color CellBackColorModified
- {
- get
- {
- return _cellBackColorModified;
- }
- set
- {
- _cellBackColorModified = value;
- }
- }
- [System.ComponentModel.Browsable(true)]
- [System.ComponentModel.DefaultValue(typeof(Color), "240, 255, 220")]
- [System.ComponentModel.Description("设定或者获取删除的Cell背景颜色。")]
- public Color CellBackColorDeleted
- {
- get
- {
- return _cellBackColorDeleted;
- }
- set
- {
- _cellBackColorDeleted = value;
- }
- }
- [System.ComponentModel.Browsable(true)]
- [System.ComponentModel.Description("设定或者获取右键菜单的内容。")]
- public ContextMenuVisibleFlags ContextMenuVisible
- {
- get
- {
- return _contextMenuVisibleFlag;
- }
- set
- {
- _contextMenuVisibleFlag = value;
- }
- }
- /// <summary>
- /// 设置输入单元格的颜色
- /// </summary>
- public bool IsSetInputColumnsColor
- {
- set
- {
- if (DataSource != null && !this.ReadOnly && this.Enabled)
- {
- for (int i = 0; i < this.Rows.Count; i++)
- {
- if (!this.Rows[i].ReadOnly)
- {
- for (int j = 0; j < this.Columns.Count; j++)
- {
- if (!this.Rows[i].Cells[this.Columns[j].Name].ReadOnly)
- {
- this.Rows[i].Cells[this.Columns[j].Name].Style.BackColor
- = ColorTranslator.FromHtml(Constant.ALLOW_MODIFY_AREA_BACKGROUND_COLOR);
- }
- else
- {
- this.Rows[i].Cells[this.Columns[j].Name].Style.BackColor = Color.White;
- }
- }
- }
- }
- }
- }
- }
- /// <summary>
- /// 设定或者获取当前DataTable
- /// </summary>
- public DataTable CurrentDataTable
- {
- get
- {
- return DataConvert.ToDataTable(this.DataSource, this.DataMember);
- }
- }
- [System.ComponentModel.Browsable(true)]
- [System.ComponentModel.DefaultValue(typeof(bool), "true")]
- [System.ComponentModel.Description("设定或者获取是否显示行数选项。")]
- public bool IsDispRowCount
- {
- get
- {
- return _isDispRowCount;
- }
- set
- {
- _isDispRowCount = value;
- }
- }
- [Description("设置多维表头时,设置动态列")]
- public string DynamicColumnName
- {
- get
- {
- return this._dynamicColumnName;
- }
- set
- {
- this._dynamicColumnName = value;
- }
- }
- [Description("设置多维表头时,设置的子列名称")]
- public string[] ChildNodeColumnName
- {
- get
- {
- return this._childNodeColumnName;
- }
- set
- {
- this._childNodeColumnName = value;
- }
- }
- [Description("设置多维表头时,设置的子列显示名称")]
- public string[] ChildNodeColumnText
- {
- get
- {
- return this._childNodeColumnText;
- }
- set
- {
- this._childNodeColumnText = value;
- }
- }
- [Description("是否设置节点")]
- public bool HasNode
- {
- get
- {
- return this._isHasNode;
- }
- set
- {
- this._isHasNode = value;
- }
- }
- public new object DataSource
- {
- get
- {
- return base.DataSource;
- }
- set
- {
- try
- {
- if (value != null)
- {
- dt = (DataTable)value;
- // 设置列头显示的形式
- if (this.RowHeadersVisible)
- {
- this.RowHeadersWidth = 50;
- if (dt.Rows.Count > 999)
- {
- this.RowHeadersWidth += (dt.Rows.Count.ToString().Length - 3) * 15;
- }
- }
- }
- else
- {
- this.RowHeadersWidth = 50;
- // 如果数据源为空,并且是打开了合计行的,需要重新计算合计行的值
- if (_isOpenTotalRow && base.DataSource != null)
- {
- dt = ((DataTable)base.DataSource).Clone();
- if (this.ReadOnly && this.AllowUserToAddRows)
- {
- this.AllowUserToAddRows = false;
- }
- //CountTotalRow();
- }
- //if (_isOpenTotalRow && base.DataSource == null)
- //{
- // CountTotalRow();
- //}
- if (_isOpenTotalRow)
- {
- ClearTotalRowData();
- }
- }
- // 根据列名去设置树形结构
- if (HasNode && value != null && !string.IsNullOrEmpty(NodeColumnName))
- {
- this.Nodes.Clear();
- DataRow[] dataRows = null;
- TreeGridNode node = null;
- DataRow[] dataRowsTmp = null;
- DataTable dataTable = (DataTable)value;
- SortedList<int, string> sortedlist = new SortedList<int, string>();
- dataRows = dataTable.Select(" ParentID = 0");
- for (int i = 0; i < dataRows.Length; i++)
- {
- node = this.Nodes.Add(dataRows[i], dataTable.Columns, this.Columns, sortedlist, out sortedlist);
- dataRowsTmp = dataTable.Select(" ParentID = " + dataRows[i][NodeColumnName]);
- InitNode(dataTable, node, sortedlist, dataRowsTmp);
- }
- // Control when edit occurs because edit mode shouldn't start when expanding/collapsing
- //this.EditMode = DataGridViewEditMode.EditProgrammatically;
- this.RowTemplate = new TreeGridNode() as DataGridViewRow;
- // This sample does not support adding or deleting rows by the user.
- this.AllowUserToAddRows = false;
- this.AllowUserToDeleteRows = false;
- }
- // 动态生成多维表头(目前只支持2维)
- else if (!string.IsNullOrEmpty(DynamicColumnName) && value != null
- && ChildNodeColumnName != null && ChildNodeColumnName.Length > 0)
- {
- DataTable dataTable = (DataTable)value;
- ArrayList dynamicnames = new ArrayList();
- for (int i = 0; i < dataTable.Rows.Count; i++)
- {
- if (!dynamicnames.Contains(dataTable.Rows[i][DynamicColumnName]))
- {
- dynamicnames.Add(dataTable.Rows[i][DynamicColumnName]);
- }
- }
- DataTable tmpTable = LoadColumnHeaderTree(dynamicnames);
- this.ColumnDeep = 2;
- this.ColumnHeadersHeightSizeMode =
- DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
- this.ScrollBars = ScrollBars.Both;
- //base.DataSource = value;
- tmpTable = BindData(dataTable, tmpTable, dynamicnames);
- this.RowCount = tmpTable.Rows.Count;
- base.DataSource = tmpTable;
- }
- else
- {
- base.DataSource = value;
- this.ClearSelection();
- }
- // 设置交替行颜色
- if (IsOpenMergeCellFlag )
- {
- this.SetDataGridViewRowColor();
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- }
- [Browsable(false)]
- [DefaultValue(false)]
- public bool IsChildDGV
- {
- get
- {
- return _isChildDGV;
- }
- set
- {
- _isChildDGV = value;
- }
- }
- [Browsable(false)]
- public string ViewRowFilter
- {
- get
- {
- return _viewRowFilterString;
- }
- set
- {
- _viewRowFilterString = value;
- }
- }
- public int CellHeight
- {
- get
- {
- return _cellHeight;
- }
- set
- {
- _cellHeight = value;
- }
- }
- public bool RefreshAtHscroll
- {
- get
- {
- return _hscrollRefresh;
- }
- set
- {
- _hscrollRefresh = value;
- }
- }
- [Description("设置或获得合并表头数的深度")]
- public int ColumnDeep
- {
- get
- {
- if (this.Columns.Count == 0)
- {
- _columnDeep = 1;
- }
- this.ColumnHeadersHeight = _cellHeight * _columnDeep;
- return _columnDeep;
- }
- set
- {
- if (value < 1)
- {
- _columnDeep = 1;
- }
- else
- {
- _columnDeep = value;
- }
- this.ColumnHeadersHeight = _cellHeight * _columnDeep;
- }
- }
- [Description("添加合并式单元格绘制的所需要的节点对象")]
- public TreeView[] ColumnTreeView
- {
- get
- {
- return _columnTreeView;
- }
- set
- {
- //if (_columnTreeView != null)
- //{
- // for (int i = 0; i <=_columnTreeView.Length -1; i++)
- // {
- // _columnTreeView[i].Dispose();
- // }
- //}
- _columnTreeView = value;
- }
- }
- [Description("设置添加的字段数的相关属性")]
- public TreeView ColumnTreeViewNode
- {
- get
- {
- if (_columnTreeView != null && _columnTreeView.Length > 0 && _columnTreeView[0] != null)
- {
- return _columnTreeView[0];
- }
- return null;
- }
- }
- public ArrayList ColumnList
- {
- get
- {
- if (_columnTreeView == null)
- {
- return null;
- }
- if (_columnTreeView[0] == null)
- {
- return null;
- }
- if (_columnTreeView[0].Nodes == null)
- {
- return null;
- }
- if (_columnTreeView[0].Nodes.Count == 0)
- {
- return null;
- }
- _columnList.Clear();
- GetColumnNodes(_columnList, _columnTreeView[0].Nodes[0], false);
- return _columnList;
- }
- }
- public new DataGridViewRowCollection Rows
- {
- get { return base.Rows; }
- }
- public new DataGridViewRow RowTemplate
- {
- get { return base.RowTemplate; }
- set { base.RowTemplate = value; }
- }
- [DefaultValue(true)]
- public bool ShowLines
- {
- get { return this._showLines; }
- set
- {
- if (value != this._showLines)
- {
- this._showLines = value;
- this.Invalidate();
- }
- }
- }
- public new int RowCount
- {
- get
- {
- return base.RowCount;
- }
- set
- {
- base.RowCount = value;
- }
- }
- [Description("是否能导出excel")]
- [DefaultValue(true)]
- public bool IsExportFlag
- {
- set;
- get;
- }
- [DefaultValue(true)]
- public bool IsProcessRightFlag
- {
- get;
- set;
- }
- [DefaultValue(false)]
- public bool IsSelectGoodsFlag
- {
- get;
- set;
- }
- /// <summary>
- /// 需要进行合计的列,如果没有,就是所有的可以的合计的列都合计
- /// </summary>
- public List<string> TotalSumColumns
- {
- get;
- set;
- }
- /// <summary>
- /// 是否自动计算合计行,默认是自动
- /// </summary>
- public bool IsAutoCountSum
- {
- get;
- set;
- }
- /// <summary>
- /// 是否有小计,在有合计行时使用
- /// </summary>
- public bool IsSubTotalFlag
- {
- get;
- set;
- }
- /// <summary>
- /// 是否点了自适应列宽
- /// </summary>
- public bool IsAutoResizeColumns
- {
- get;
- set;
- }
- /// <summary>
- /// 是否点击F12隐藏
- /// </summary>
- public bool IsClickF12
- {
- get;
- set;
- }
- [Description("设置树形结构时,需要设置关系的主键ID名称")]
- public string NodeColumnName
- {
- get
- {
- return this._nodeColumnName;
- }
- set
- {
- this._nodeColumnName = value;
- }
- }
- public TreeGridNodeCollection Nodes
- {
- get
- {
- return this._root.Nodes;
- }
- }
- public TreeGridNode CurrentRowT
- {
- get
- {
- return base.CurrentRow as TreeGridNode;
- }
- }
- [Description("Causes nodes to always show as expandable. Use the NodeExpanding event to add nodes.")]
- public bool VirtualNodes
- {
- get { return _virtualNodes; }
- set { _virtualNodes = value; }
- }
- public TreeGridNode CurrentNode
- {
- get
- {
- return this.CurrentRowT;
- }
- }
- public ImageList ImageList
- {
- get { return this._imageList; }
- set
- {
- this._imageList = value;
- //TODO: should we invalidate cell styles when setting the image list?
- }
- }
- /// <summary>
- /// 用合计的值进行计算值 的列
- /// </summary>
- public string TotalCountName
- {
- get;
- set;
- }
- /// <summary>
- /// 用合计的值进行计算 的公式
- /// </summary>
- public string TotalCountFormula
- {
- get;
- set;
- }
- /// <summary>
- /// 需要合并的列(周兴 2015-12-6 修改)
- /// </summary>
- public List<string> MergeColumnNames
- {
- get;
- set;
- }
- /// <summary>
- /// 需要合并的列(明细,必须在上面属性中也存在,这个属性类似于子属性)(周兴 2015-12-6 修改)
- /// </summary>
- public List<string> MergeDetailColumnNames
- {
- get;
- set;
- }
- /// <summary>
- /// 合并单元格时需要唯一列(比如SalesID,不同的SalesID的是不允许合并在一起的
- /// </summary>
- public string MergeOnlyColumn
- {
- get;
- set;
- }
- /// <summary>
- /// 合并单元格时需要唯一列(子列)(比如DetailID,相同SalesID的不同DetailID也是不允许合并的
- /// </summary>
- public string MergeDetailOnlyColumn
- {
- get;
- set;
- }
- /// <summary>
- /// 合并单元格时需要唯一列(子列)(比如DetailID,相同SalesID的不同DetailID也是不允许合并的
- /// </summary>
- public string MergeDDetailOnlyColumn
- {
- get;
- set;
- }
- /// <summary>
- /// 需要合并的列(明细,必须在上面属性中也存在,这个属性类似于子属性)(周兴 2015-12-6 修改)
- /// </summary>
- public List<string> MergeDDetailColumnNames
- {
- get;
- set;
- }
- /// <summary>
- /// 是否开启合并单元格
- /// </summary>
- public bool IsOpenMergeCellFlag
- {
- get;
- set;
- }
- /// <summary>
- /// 是否打印
- /// </summary>
- public bool IsPrintFlag
- {
- get;
- set;
- }
- #endregion
- #region 构造函数
- public dkDataGridView()
- {
- InitializeComponent();
- this.Tag = true;
- IsProcessRightFlag = true;
- IsSelectGoodsFlag = false;
- IsAutoCountSum = true;
- IsExportFlag = true;
- IsAutoResizeColumns = false;
- IsSubTotalFlag = false;
- this.Rows.CollectionChanged +=
- new System.ComponentModel.CollectionChangeEventHandler(Rows_CollectionChanged);
- this._mnuFrozen.Name = "mnuFrozen";
- this._mnuFrozen.Size = new System.Drawing.Size(143, 22);
- this._mnuFrozen.Text = DKResources.ControlsTips.DK_DataGridView_Frozen;
- this._mnuFrozen.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M001;
- this._mnuRefine.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M002;
- this._mnuFilter.Name = "mnuFilter";
- this._mnuFilter.Size = new System.Drawing.Size(118, 22);
- this._mnuFilter.Text = DKResources.ControlsTips.DK_DataGridView_Filter;
- this._mnuFilter.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M003;
- this._mnuFilterExcept.Name = "mnuFilterExcept";
- this._mnuFilterExcept.Size = new System.Drawing.Size(143, 22);
- this._mnuFilterExcept.Text = DKResources.ControlsTips.DK_DataGridView_FilterExcept;
- this._mnuFilterExcept.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M004;
- this._mnuUnfilter.Name = "mnuUnfilter";
- this._mnuUnfilter.Size = new System.Drawing.Size(143, 22);
- this._mnuUnfilter.Text = DKResources.ControlsTips.DK_DataGridView_Unfilter;
- this._mnuUnfilter.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M005;
- this._mnuOutputFile.Name = "mnuOutputFile";
- this._mnuOutputFile.Size = new System.Drawing.Size(143, 22);
- this._mnuOutputFile.Text = DKResources.ControlsTips.DK_DataGridView_OutputFile;
- // 周兴 2016-7-22 增加 输出excel
- this._mnuOutputFileXls.Name = "mnuOutputFileXls";
- this._mnuOutputFileXls.Size = new System.Drawing.Size(143, 22);
- this._mnuOutputFileXls.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M008;
- this._mnuOutputFileXls.Text = DKResources.ControlsTips.DK_DataGridView_OutputFileXLs;
- this._mnuDelete.Name = "mnuDelete";
- this._mnuDelete.Size = new System.Drawing.Size(143, 22);
- this._mnuDelete.Text = DKResources.ControlsTips.DK_DataGridView_DeleteRow;
- this._mnuDelete.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M006;
- this._mnuPrint.Name = "mnuPrint";
- this._mnuPrint.Size = new System.Drawing.Size(143, 22);
- this._mnuPrint.Text = DKResources.ControlsTips.DK_DataGridView_Print;
- this._mnuPrint.ToolTipText = DKResources.ControlsTips.TOOLTIP_DataGridView_M007;
- // 事件
- this._mnuRefine.RefineTextFixed += new EventHandler(mnuRefine_RefineTextFixed);
- this._mnuFilter.Click += new EventHandler(mnuFilter_Click);
- this._mnuFilterExcept.Click += new EventHandler(mnuFilterExcept_Click);
- this._mnuUnfilter.Click += new EventHandler(mnuUnfilter_Click);
- this._mnuOutputFile.Click += new EventHandler(mnuOutputFile_Click);
- this._mnuOutputFileXls.Click += new EventHandler(mnuOutputFileXls_Click);
- this._mnuFrozen.Click += new EventHandler(mnuFrozen_Click);
- this._mnuDelete.Click += new EventHandler(mnuDelete_Click);
- this._mnuPrint.Click += new EventHandler(mnuPrint_Click);
- //// Control when edit occurs because edit mode shouldn't start when expanding/collapsing
- //this.EditMode = DataGridViewEditMode.EditProgrammatically;
- //this.RowTemplate = new TreeGridNode() as DataGridViewRow;
- //// This sample does not support adding or deleting rows by the user.
- //this.AllowUserToAddRows = false;
- //this.AllowUserToDeleteRows = false;
- this.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
- this.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing;
- this.RowHeadersWidth = 50;
- this._root = new TreeGridNode(this);
- this._root.IsRoot = true;
- //// Ensures that all rows are added unshared by listening to the CollectionChanged event.
- //base.Rows.CollectionChanged += delegate(object sender, System.ComponentModel.CollectionChangeEventArgs e) { };
- }
- #endregion
- #region 公开方法/函数
- public CurrencyManager GetCurrencyManager()
- {
- if (this.DataSource == null)
- {
- return null;
- }
- return this.BindingContext[this.DataSource, this.DataMember] as CurrencyManager;
- }
- public DataTable GetDataTable()
- {
- CurrencyManager bindingManager = GetCurrencyManager();
- if (bindingManager == null)
- {
- return null;
- }
- DataView dataView = bindingManager.List as DataView;
- if (dataView == null)
- {
- return null;
- }
- return dataView.Table;
- }
- public DataRowView GetDataRowView(int viewRowIndex)
- {
- if (viewRowIndex < 0)
- {
- return null;
- }
- if (this.DataSource == null)
- {
- return null;
- }
- try
- {
- CurrencyManager bindingManager = GetCurrencyManager();
- if (bindingManager != null)
- {
- if (viewRowIndex < bindingManager.List.Count)
- {
- return (bindingManager.List[viewRowIndex] as DataRowView);
- }
- }
- }
- catch (Exception ex)
- {
- Debug.Assert(false, "Error", ex.Message);
- }
- return null;
- }
- public DataRow GetDataRow(int viewRowIndex)
- {
- DataRowView rowView = GetDataRowView(viewRowIndex);
- if (rowView == null)
- {
- return null;
- }
- if (rowView.Row == null)
- {
- return null;
- }
- return rowView.Row;
- }
- public int GetDataRowIndex(int viewRowIndex)
- {
- DataRow row = GetDataRow(viewRowIndex);
- if (row == null)
- {
- return -1;
- }
- return row.Table.Rows.IndexOf(row);
- }
- public int GetViewColumnIndex(string dataColumnName)
- {
- for (int i = 0; i < this.Columns.Count; i++)
- {
- DataGridViewColumn column = this.Columns[i];
- string dataPropartyName = column.DataPropertyName;
- if (dataColumnName.Equals(dataPropartyName))
- {
- return i;
- }
- }
- return -1;
- }
- public void OutputFile()
- {
- OutputFile(true);
- }
- public void SetFrozen()
- {
- int selectRow = _gridRowIndex;
- int selectCol = _gridColumnindex;
- bool isSelectSameCell = true;
- // 清除冻结
- if (0 < this.Rows.Count)
- {
- this.Rows[0].Frozen = false;
- }
- if (0 < this.Columns.Count)
- {
- this.Columns[0].Frozen = false;
- }
- // 是否选择了同一个单元格
- isSelectSameCell = IsSelectSameCell(selectRow, selectCol);
- if (isSelectSameCell && _isFrozen)
- {
- _isFrozen = false;
- return;
- }
- _isFrozen = false;
- if (0 < selectRow)
- {
- // 行冻结处理
- this.Rows[selectRow - 1].Frozen = true;
- _isFrozen = true;
- }
- if (0 < selectCol)
- {
- // 列冻结处理
- //this.Columns[selectCol - 1].Frozen = true;
- if (this.ColumnTreeViewNode != null && this.ColumnTreeViewNode.Nodes.Count > 0 && _columnDeep > 1)
- {
- // 说明是多维表头
- foreach (TreeNode node in this.ColumnTreeViewNode.Nodes)
- {
- if (this.Columns[selectCol].Name.Equals(node.Name))
- {
- this.Columns[node.Index].Frozen = true;
- break;
- }
- else
- {
- if (node.Nodes != null)
- {
- foreach (TreeNode childNode in node.Nodes)
- {
- if (this.Columns[selectCol].Name.Equals(childNode.Name))
- {
- this.Columns[node.LastNode.Name].Frozen = true;
- return;
- }
- }
- }
- }
- }
- }
- else
- {
- foreach (DataGridViewColumn column in this.Columns)
- {
- if (selectCol == column.Index)
- {
- this.Columns[column.DisplayIndex - 1].Frozen = true;
- break;
- }
- }
- }
- if (_isOpenTotalRow)
- {
- _columnInfos = GetDataGridViewColumnInfos();
- if (_columnInfos != null)
- {
- this.HorizontalScrollingOffset = 0;
- for (int i = 0; i < _columnInfos.Length; i++)
- {
- if (_columnInfos[i].Visible)
- {
- NewText(_columnInfos[i].DataPropertyName, i);
- }
- }
- CountTotalRow();
- }
- }
- _isFrozen = true;
- }
- // 当前选择的行号和列号
- _selectCellRowCol[0] = selectRow;
- _selectCellRowCol[1] = selectCol;
- }
- public void OutputFile(bool isAllCells)
- {
- try
- {
- SaveFileDialog dialog = new SaveFileDialog();
- dialog.Filter = "csv file (*.csv)|*.csv";
- if (dialog.ShowDialog() == DialogResult.OK)
- {
- string csv = ToCsvString(true, false, true, isAllCells);
- if (!string.IsNullOrEmpty(csv))
- {
- System.IO.FileInfo fileInfo = new System.IO.FileInfo(dialog.FileName);
- System.IO.FileStream fileStream = fileInfo.Create();
- Byte[] buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(csv);
- fileStream.Write(buffer, 0, buffer.Length);
- fileStream.Dispose();
- }
- }
- }
- catch (Exception ex)
- {
- //
- }
- }
- /// <summary>
- /// 导出excel
- /// </summary>
- public void OutputFileXls()
- {
- try
- {
- string sheetName = string.Empty;
- string fileName = string.Empty;
- bool flag = true;
- Control control = this.Parent;
- while (flag)
- {
- if (control != null && control is TabPage)
- {
- sheetName = control.Text;
- }
- if (control != null && control is Form)
- {
- fileName = control.Text;
- if (string.IsNullOrEmpty(sheetName))
- {
- sheetName = fileName;
- }
- flag = false;
- }
- control = control.Parent;
- if (control == null)
- {
- flag = false;
- }
- }
- TreeView tv = null;
- if (_columnTreeView != null && _columnTreeView.Length > 0)
- {
- tv = _columnTreeView[0];
- }
- Common.Instance.ExportExcel(this, tv, null, fileName, fileName, this.Font, "", this.Font, "", sheetName, true, true);
- }
- catch (Exception ex)
- {
- //
- }
- }
- public string GetColumnIndex(int columnIndex)
- {
- if (_columnInfos == null)
- {
- _columnInfos = GetDataGridViewColumnInfos();
- }
- if (columnIndex > _columnInfos.Length -1 )
- {
- return string.Empty;
- }
- return _columnInfos[columnIndex].DataPropertyName;
- }
- public string ToCsvString(bool isHeaderFirstRow, bool isTsv,
- bool isFormattedValue, bool isAllCells)
- {
- if (this.CurrentCell != null)
- {
- if (this.CurrentCell.IsInEditMode && !(
- this.CurrentCell is DataGridViewCheckBoxCell))
- {
- return null;
- }
- }
- if (CurrentDataTable == null)
- {
- return null;
- }
- DataTable table = new DataTable();
- List<int> columnIndexList;
- int rowIndexMin, rowIndexMax;
- DataGridViewColumnInfo[] columnInfo = null;
- if (isAllCells)
- {
- columnIndexList = new List<int>();
- columnInfo = this.GetDataGridViewColumnInfos();
- //for (int i = 0; i < columnInfo.Length; i++)
- //{
- // columnIndexList.Add(i);
- //}
- //for (int i = 0; i < this.Columns.Count; i++)
- //{
- // if (this.Columns[i].Visible)
- // {
- // columnIndexList.Add(this.Columns[i].DisplayIndex);
- // }
- //}
- rowIndexMin = 0;
- rowIndexMax = this.Rows.Count - 1;
- if (this.AllowUserToAddRows)
- {
- rowIndexMax -= 1;
- }
- }
- else
- {
- GetSelectedRange(out columnIndexList, out rowIndexMin, out rowIndexMax);
- }
- List<int> invalidColumnList = new List<int>();
- //foreach (int columnIndex in columnIndexList)
- //{
- // string columnName = this.Columns[columnIndex].Name;
- // DataGridViewColumn column = this.Columns[columnName];
- // if (column == null)
- // {
- // invalidColumnList.Add(columnIndex);
- // continue;
- // }
- // if (!isFormattedValue && column.CellType.Name ==
- // "DataGridViewSearchFileBoxCellEx")
- // {
- // invalidColumnList.Add(columnIndex);
- // continue;
- // }
- // DataColumn dcolColumn = new DataColumn(column.Name);
- // dcolColumn.Caption = column.HeaderText;
- // table.Columns.Add(dcolColumn);
- //}
- //foreach (int columnIndex in invalidColumnList)
- //{
- // columnIndexList.Remove(columnIndex);
- //}
- if (columnInfo != null)
- {
- for (int i = 0; i < columnInfo.Length; i++)
- {
- DataColumn dcolColumn = new DataColumn(columnInfo[i].ColumnName);
- dcolColumn.Caption = columnInfo[i].TreeColumnText;
- table.Columns.Add(dcolColumn);
- }
- }
- DataRow drowRow;
- for (int i = rowIndexMin; i <= rowIndexMax; i++)
- {
- drowRow = table.NewRow();
- DataGridViewRow rowView = this.Rows[i];
- if (rowView != null)
- {
- int j = 0;
- for (int k = 0; k < columnInfo.Length; k++)
- {
- DataGridViewCell cell = rowView.Cells[columnInfo[k].ColumnName];
- object value;
- if (isFormattedValue)
- {
- value = cell.FormattedValue;
- }
- else
- {
- value = cell.Value;
- }
- // 周兴 2015-11-19 如果前几个都是0,导出csv就会消失
- if ("String".Equals(cell.ValueType.Name) && (cell.Value + "").StartsWith("0"))
- {
- value = ((char)(9)).ToString() + value;
- }
- //周兴 2016-3-22 修改
- if ("String".Equals(cell.ValueType.Name) && (cell.Value + "").IndexOf("-") > 0)
- {
- value = ((char)(9)).ToString() + value;
- }
-
- //if (!string.IsNullOrEmpty(value + "") && value.ToString().StartsWith("-"))
- //{
- // value = "'" + value;
- //}
- CsvConvertingEventArgs e = new CsvConvertingEventArgs(k, value);
- OnCsvCoverting(e);
- drowRow[j] = e.Value;
- j++;
- }
- table.Rows.Add(drowRow);
- }
- }
- // 周兴 2015-11-24 如果有合计把合计行也显示进来
- if (_isOpenTotalRow)
- {
- try
- {
- drowRow = table.NewRow();
- TextBox tempTB;
- bool flag = false;
- for (int k = 0; k < columnInfo.Length; k++)
- {
- tempTB = findTextBox("txt" + columnInfo[k].DataPropertyName);
- if (tempTB != null && table.Columns.Contains(columnInfo[k].DataPropertyName))
- {
- if (!flag && "".Equals(tempTB.Text))
- {
- drowRow[columnInfo[k].DataPropertyName] = "合计";
- flag = true;
- }
- else
- {
- drowRow[columnInfo[k].DataPropertyName] = tempTB.Text;
- }
- }
- }
- table.Rows.Add(drowRow);
- }
- catch (Exception ex)
- {
-
- }
- }
- // DataTable情報をcsv形式に変換
- Char delim = ',';
- if (isTsv)
- {
- delim = '\t';
- }
- return CsvManager.ToString(table, isHeaderFirstRow, delim, '\"');
- }
- /// <summary>
- /// 绘制合并表头
- /// </summary>
- /// <param name="node">合并表头节点</param>
- /// <param name="e">绘图参数集</param>
- /// <param name="level">节点深度</param>
- public void PaintUnitHeader(TreeNode node, DataGridViewCellPaintingEventArgs e, int level)
- {
- // 根节点退出递归调用
- if (level == 0)
- {
- return;
- }
- RectangleF uhRectangle;
- int uhWidth;
- using (
- SolidBrush gridBrush = new SolidBrush(this.GridColor),
- backColorBrush = new SolidBrush(e.CellStyle.BackColor))
- {
- using (Pen gridLinePen = new Pen(gridBrush))
- {
- StringFormat textFormat = new StringFormat();
- textFormat.Alignment = StringAlignment.Center;
- uhWidth = GetUnitHeaderWidth(node);
- if (node.Nodes.Count == 0)
- {
- uhRectangle = new RectangleF(e.CellBounds.Left, e.CellBounds.Top + node.Level * _cellHeight,
- uhWidth - 1, _cellHeight * (_columnDeep - node.Level) - 1);
- }
- else
- {
- uhRectangle = new RectangleF(e.CellBounds.Left, e.CellBounds.Top + node.Level * _cellHeight,
- uhWidth - 1, _cellHeight - 1);
- }
- // 画矩形
- e.Graphics.FillRectangle(backColorBrush, uhRectangle);
- // 画底线
- e.Graphics.DrawLine(gridLinePen, uhRectangle.Left,
- uhRectangle.Bottom, uhRectangle.Right, uhRectangle.Bottom);
- // 画右端线
- e.Graphics.DrawLine(gridLinePen, uhRectangle.Right,
- uhRectangle.Top, uhRectangle.Right, uhRectangle.Bottom);
- if (!string.IsNullOrEmpty(node.Text))
- {
- float tmpWidth = uhRectangle.Width / 2;
- if (this.Parent != null)
- {
- if (uhRectangle.Width - this.HorizontalScrollingOffset > this.Parent.Width)
- {
- tmpWidth = (this.Parent.Width - uhRectangle.Left) / 2;
- }
- else
- {
- tmpWidth = uhRectangle.Width / 2;
- }
- }
- e.Graphics.DrawString(node.Text, this.Font, new SolidBrush(e.CellStyle.ForeColor),
- uhRectangle.Left + tmpWidth
- - e.Graphics.MeasureString(node.Text, this.Font).Width / 2 - 1,
- uhRectangle.Top + uhRectangle.Height / 2
- - e.Graphics.MeasureString(node.Text, this.Font).Height / 2);
- }
- if (node.PrevNode == null)
- {
- if (node.Parent != null)
- {
- PaintUnitHeader(node.Parent, e, level - 1);
- }
- }
- // 周兴 20141116 修改
- else
- {
- if (node != null && node.Parent != null)
- {
- // 最后一个节点才去判断父节点是否已经重绘
- if (node.Parent.LastNode.Name.Equals(node.Name))
- {
- string name = node.Parent.FirstNode.Name;
- if (this.Columns.Contains(name) && !this.Columns[name].Visible)
- {
- PaintUnitHeader(node.Parent, e, level - 1);
- }
- }
- }
- }
- }
- }
- }
- #endregion
- #region 私有方法
- /// <summary>
- /// 设置列表的背景颜色
- /// </summary>
- public void SetDataGridViewRowColor()
- {
- try
- {
- // 只有开启了合并行才行
- if (IsOpenMergeCellFlag && !string.IsNullOrEmpty(MergeOnlyColumn))
- {
- List<string> rowColor = new List<string>();
- rowColor.Add(Constant.OA_COLOR_WHITE);
- rowColor.Add(Constant.OA_COLOR_GREY);
- int id = 0;
- int j = 0;
- for (int i = 0; i < this.Rows.Count; i++)
- {
- if (!string.IsNullOrEmpty(this.Rows[i].Cells[MergeOnlyColumn].Value + ""))
- {
- if (i == 0)
- {
- id = Convert.ToInt32(this.Rows[i].Cells[MergeOnlyColumn].Value);
- }
- else
- {
- if (id != Convert.ToInt32(this.Rows[i].Cells[MergeOnlyColumn].Value))
- {
- if (j == 0)
- {
- j = 1;
- }
- else
- {
- j = 0;
- }
- }
- id = Convert.ToInt32(this.Rows[i].Cells[MergeOnlyColumn].Value);
- }
- this.Rows[i].DefaultCellStyle.BackColor = ColorTranslator.FromHtml(rowColor[j]);
- this.Rows[i].Cells[MergeOnlyColumn].Tag = rowColor[j];
- }
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- private DataTable BindData(DataTable dataTable, DataTable tmpTable, ArrayList dynamicnames)
- {
- for (int i = 0; i < dataTable.Rows.Count; i++)
- {
- DataRow row = null;
- if (tmpTable.Rows.Count > 0)
- {
- for (int j = 0; j < tmpTable.Rows.Count; j++)
- {
- bool isNewRow = true;
- for (int t = 0; t < dataTable.Columns.Count; t++)
- {
- if (tmpTable.Columns.Contains(dataTable.Columns[t].ColumnName))
- {
- if (tmpTable.Rows[j][dataTable.Columns[t].ColumnName]
- == dataTable.Rows[i][dataTable.Columns[t].ColumnName])
- {
- isNewRow = false;
- }
- else
- {
- isNewRow = true;
- break;
- }
- }
- }
- if (!isNewRow)
- {
- row = tmpTable.Rows[j];
- }
- }
- if (row == null)
- {
- row = tmpTable.NewRow();
- SetDataToTable(row, i, dataTable, dynamicnames);
- tmpTable.Rows.Add(row);
- }
- else
- {
- SetDataToTable(row, i, dataTable, dynamicnames);
- }
- }
- else
- {
- row = tmpTable.NewRow();
- SetDataToTable(row, i, dataTable, dynamicnames);
- tmpTable.Rows.Add(row);
- }
- }
- return tmpTable;
- }
- private void SetDataToTable(DataRow row, int i, DataTable dataTable, ArrayList dynamicnames)
- {
- for (int t = 0; t < dataTable.Columns.Count; t++)
- {
- if (this.Columns.Contains(dataTable.Columns[t].ColumnName))
- {
- row[dataTable.Columns[t].ColumnName] =
- dataTable.Rows[i][dataTable.Columns[t].ColumnName];
- }
- else
- {
- if (!DynamicColumnName.Equals(dataTable.Columns[t].ColumnName))
- {
- for (int j = 0; j < dynamicnames.Count; j++)
- {
- if (dynamicnames[j].Equals(dataTable.Rows[i][DynamicColumnName]))
- {
- row[dataTable.Columns[t].ColumnName + (j + 1)]
- = dataTable.Rows[i][dataTable.Columns[t].ColumnName];
- }
- }
- }
- }
- }
- }
- private DataTable LoadColumnHeaderTree(ArrayList dynamicnames)
- {
- TreeView treeview = new TreeView();
- DataGridViewColumnCollection tempColumns = this.Columns;
- DataTable tmpTable = new DataTable();
- for (int i = 0; i < tempColumns.Count; i++)
- {
- if (DynamicColumnName.Equals(tempColumns[i].Name))
- {
- int x = 0;
- for (int j = 0; j < dynamicnames.Count; j++)
- {
- TreeNode rootNode = new TreeNode(dynamicnames[j] + "");
- rootNode.Text = dynamicnames[j] + "";
- rootNode.Name = tempColumns[j].Name;
- treeview.Nodes.Add(rootNode);
- for (int t = 0; t < ChildNodeColumnName.Length; t++)
- {
- x++;
- DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
- column.Name = ChildNodeColumnName[t] + (j + 1);
- column.DataPropertyName = ChildNodeColumnName[t] + (j + 1);
- column.HeaderText = ChildNodeColumnText[t];
- this.Columns.Insert(i + x, column);
- tmpTable.Columns.Add(new DataColumn(column.Name));
- TreeNode node = new TreeNode(ChildNodeColumnName[t]);
- node.Text = ChildNodeColumnText[t];
- node.Name = ChildNodeColumnName[t];
- rootNode.Nodes.Add(node);
- }
- }
- this.Columns.Remove(DynamicColumnName);
- }
- else
- {
- if (!tmpTable.Columns.Contains(tempColumns[i].Name))
- {
- tmpTable.Columns.Add(new DataColumn(tempColumns[i].Name));
- TreeNode rootNode = new TreeNode(tempColumns[i].Name);
- rootNode.Text = this.Columns[i].HeaderText;
- rootNode.Name = tempColumns[i].Name;
- treeview.Nodes.Add(rootNode);
- }
- }
- }
- this.ColumnTreeView = new TreeView[] { treeview };
- return tmpTable;
- }
- /// <summary>
- /// 获得合并标题字段的宽度
- /// </summary>
- /// <param name="node"></param>
- /// <returns></returns>
- private int GetUnitHeaderWidth(TreeNode node)
- {
- int uhWidth = 0;
- if (node.Nodes == null || node.Nodes.Count == 0)
- {
- return this.Columns[GetColumnListNodeIndex(node)].Width;
- }
- for (int i = 0; i <= node.Nodes.Count - 1; i++)
- {
- //if (this.Columns[node.Nodes[i].Name].Visible)
- //{
- uhWidth = uhWidth + GetUnitHeaderWidth(node.Nodes[i]);
- //}
- }
- return uhWidth;
- }
- /// <summary>
- /// 获得底层字段索引
- /// </summary>
- /// <param name="node"></param>
- /// <returns></returns>
- private int GetColumnListNodeIndex(TreeNode node)
- {
- for (int i = 0; i <= _columnList.Count - 1; i++)
- {
- if (((TreeNode)_columnList[i]).Equals(node))
- {
- return i;
- }
- }
- return -1;
- }
- private void GetColumnNodes(ArrayList alList, TreeNode node, bool isChecked)
- {
- if (!isChecked)
- {
- if (node.FirstNode == null)
- {
- alList.Add(node);
- if (node.NextNode != null)
- {
- GetColumnNodes(alList, node.NextNode, false);
- return;
- }
- if (node.Parent != null)
- {
- GetColumnNodes(alList, node.Parent, true);
- return;
- }
- }
- else
- {
- if (node.FirstNode != null)
- {
- GetColumnNodes(alList, node.FirstNode, false);
- return;
- }
- }
- }
- else
- {
- if (node.FirstNode == null)
- {
- return;
- }
- if (node.NextNode != null)
- {
- GetColumnNodes(alList, node.NextNode, false);
- return;
- }
- if (node.Parent != null)
- {
- GetColumnNodes(alList, node.Parent, true);
- return;
- }
- }
- }
- /// <summary>
- /// 画单元格(合并单元格 周兴 2015-12-6 增加)
- /// </summary>
- /// <param name="e"></param>
- private void DrawCell(DataGridViewCellPaintingEventArgs e)
- {
- // 只有开启的才允许
- if (!this.IsOpenMergeCellFlag || this.MergeColumnNames == null || this.MergeColumnNames.Count == 0
- || string.IsNullOrEmpty(MergeOnlyColumn) || !this.Columns.Contains(MergeOnlyColumn) || this.CurrentRow == null)
- {
- return;
- }
- if (e.CellStyle.Alignment == DataGridViewContentAlignment.NotSet)
- {
- e.CellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
- }
- Brush gridBrush = new SolidBrush(this.GridColor);
- SolidBrush backBrush = new SolidBrush(e.CellStyle.BackColor);
- SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor);
- int cellwidth;
- //上面相同的行数
- int upRows = 0;
- //下面相同的行数
- int downRows = 0;
- //总行数
- int count = 0;
- bool deilFlag = false;
- bool isSeleted = false;
- int upHeight = 0;
- int downHeight = 0;
- bool dDetailFlag = false;
- if (MergeDetailColumnNames != null && MergeDetailColumnNames.Count > 0 && !string.IsNullOrEmpty(MergeDetailOnlyColumn))
- {
- deilFlag = true;
- }
- if (MergeDDetailColumnNames != null && MergeDDetailColumnNames.Count > 0 && !string.IsNullOrEmpty(MergeDDetailOnlyColumn))
- {
- dDetailFlag = true;
- }
- if (this.MergeColumnNames.Contains(this.Columns[e.ColumnIndex].Name) && e.RowIndex != -1)
- {
- cellwidth = e.CellBounds.Width;
- Pen gridLinePen = new Pen(gridBrush);
- string curValue = e.Value == null ? "" : e.Value.ToString().Trim();
- string mergeOnlyColumnName = this.Rows[e.RowIndex].Cells[MergeOnlyColumn].Value + "";
- string mergeDetailOnlyColumnName = string.Empty;
- if (!string.IsNullOrEmpty(MergeDetailOnlyColumn))
- {
- mergeDetailOnlyColumnName = this.Rows[e.RowIndex].Cells[MergeDetailOnlyColumn].Value + "";
- }
- string mergeDDetailOnlyColumnName = string.Empty;
- if (!string.IsNullOrEmpty(MergeDDetailOnlyColumn))
- {
- mergeDDetailOnlyColumnName = this.Rows[e.RowIndex].Cells[MergeDDetailOnlyColumn].Value + "";
- }
- string curSelected = this.CurrentRow.Cells[e.ColumnIndex].Value == null ? "" : this.CurrentRow.Cells[e.ColumnIndex].Value.ToString().Trim();
- //if (!string.IsNullOrEmpty(curValue))
- //{
- #region 获取下面的行数
- for (int i = e.RowIndex; i < this.Rows.Count; i++)
- {
- if ((this.Rows[i].Cells[e.ColumnIndex].Value + "").Equals(curValue) && mergeOnlyColumnName.Equals(this.Rows[i].Cells[MergeOnlyColumn].Value + ""))
- {
- if (dDetailFlag && MergeDDetailColumnNames.Contains(this.Columns[e.ColumnIndex].Name))
- {
- if (mergeDDetailOnlyColumnName.Equals(this.Rows[i].Cells[MergeDDetailOnlyColumn].Value + ""))
- {
- downRows++;
- isSeleted = isSeleted || this.Rows[i].Selected;
- downHeight += this.Rows[i].Height;
- if (e.RowIndex != i)
- {
- cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
- }
- }
- else
- {
- break;
- }
- }
- else if (deilFlag && MergeDetailColumnNames.Contains(this.Columns[e.ColumnIndex].Name))
- {
- if (mergeDetailOnlyColumnName.Equals(this.Rows[i].Cells[MergeDetailOnlyColumn].Value + ""))
- {
- downRows++;
- isSeleted = isSeleted || this.Rows[i].Selected;
- downHeight += this.Rows[i].Height;
- if (e.RowIndex != i)
- {
- cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
- }
- }
- else
- {
- break;
- }
- }
- //this.Rows[i].Cells[e.ColumnIndex].Selected = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;
- else
- {
- downRows++;
- isSeleted = isSeleted || this.Rows[i].Selected;
- downHeight += this.Rows[i].Height;
- if (e.RowIndex != i)
- {
- cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
- }
- }
- }
- else
- {
- break;
- }
- }
- #endregion
- #region 获取上面的行数
- for (int i = e.RowIndex; i >= 0; i--)
- {
- if ((this.Rows[i].Cells[e.ColumnIndex].Value + "").Equals(curValue) && mergeOnlyColumnName.Equals(this.Rows[i].Cells[MergeOnlyColumn].Value + ""))
- {
- if (dDetailFlag && MergeDDetailColumnNames.Contains(this.Columns[e.ColumnIndex].Name))
- {
- if (mergeDDetailOnlyColumnName.Equals(this.Rows[i].Cells[MergeDDetailOnlyColumn].Value + ""))
- {
- upRows++;
- isSeleted = isSeleted || this.Rows[i].Selected;
- upHeight += this.Rows[i].Height;
- if (e.RowIndex != i)
- {
- cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
- }
- }
- else
- {
- break;
- }
- }
- else if (deilFlag && MergeDetailColumnNames.Contains(this.Columns[e.ColumnIndex].Name))
- {
- if (mergeDetailOnlyColumnName.Equals(this.Rows[i].Cells[MergeDetailOnlyColumn].Value + ""))
- {
- upRows++;
- isSeleted = isSeleted || this.Rows[i].Selected;
- upHeight += this.Rows[i].Height;
- if (e.RowIndex != i)
- {
- cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
- }
- }
- else
- {
- break;
- }
- }
- else
- {
- //this.Rows[i].Cells[e.ColumnIndex].Selected = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected;
- upRows++;
- isSeleted = isSeleted || this.Rows[i].Selected;
- upHeight += this.Rows[i].Height;
- if (e.RowIndex != i)
- {
- cellwidth = cellwidth < this.Rows[i].Cells[e.ColumnIndex].Size.Width ? cellwidth : this.Rows[i].Cells[e.ColumnIndex].Size.Width;
- }
- }
- }
- else
- {
- break;
- }
- }
- #endregion
- count = downRows + upRows - 1;
- if (count < 2)
- {
- return;
- }
- //}
- if (this.Rows[e.RowIndex].Selected || isSeleted)
- {
- backBrush.Color = e.CellStyle.SelectionBackColor;
- fontBrush.Color = e.CellStyle.SelectionForeColor;
- }
- //以背景色填充
- e.Graphics.FillRectangle(backBrush, e.CellBounds);
- //画字符串
- //PaintingFont(e, cellwidth, upRows, downRows, count);
- string text = e.FormattedValue + "";
- if (!string.IsNullOrEmpty(text))
- {
- DataGridViewCellStyle cellStyle = e.CellStyle;
- TextFormatFlags textFormatFlags = this.ComputeTextFormatFlagsForCellStyleAlignment((this.RightToLeft == RightToLeft.Yes), cellStyle.Alignment, cellStyle.WrapMode);
- if ((textFormatFlags & TextFormatFlags.SingleLine) != TextFormatFlags.Default)
- {
- textFormatFlags |= TextFormatFlags.EndEllipsis;
- }
- Rectangle rectangle2 = new Rectangle(e.CellBounds.X, e.CellBounds.Bottom - upHeight, cellwidth, upHeight + downHeight - e.CellBounds.Height);
- int num = (cellStyle.WrapMode == DataGridViewTriState.True) ? 1 : 2;
- rectangle2.Offset(0, num);
- rectangle2.Width = rectangle2.Width;
- rectangle2.Height -= num + 1;
- if (rectangle2.Width > 0 && rectangle2.Height > 0 && rectangle2.Y >= 0 && rectangle2.X >=0)
- {
- TextRenderer.DrawText(e.Graphics, text, cellStyle.Font, rectangle2, fontBrush.Color, textFormatFlags);
- }
- }
- if (downRows == 1)
- {
- e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
- count = 0;
- }
- // 画右边线
- e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);
- e.Handled = true;
- }
- }
- private TextFormatFlags ComputeTextFormatFlagsForCellStyleAlignment(bool rightToLeft, DataGridViewContentAlignment alignment, DataGridViewTriState wrapMode)
- {
- TextFormatFlags textFormatFlags;
- if (alignment <= DataGridViewContentAlignment.MiddleCenter)
- {
- switch (alignment)
- {
- case DataGridViewContentAlignment.TopLeft:
- textFormatFlags = TextFormatFlags.Default;
- if (rightToLeft)
- {
- textFormatFlags |= TextFormatFlags.Right;
- goto IL_C0;
- }
- goto IL_C0;
- case DataGridViewContentAlignment.TopCenter:
- textFormatFlags = TextFormatFlags.HorizontalCenter;
- goto IL_C0;
- case (DataGridViewContentAlignment)3:
- break;
- case DataGridViewContentAlignment.TopRight:
- textFormatFlags = TextFormatFlags.Default;
- if (rightToLeft)
- {
- goto IL_C0;
- }
- textFormatFlags |= TextFormatFlags.Right;
- goto IL_C0;
- default:
- if (alignment != DataGridViewContentAlignment.MiddleLeft)
- {
- if (alignment == DataGridViewContentAlignment.MiddleCenter)
- {
- textFormatFlags = (TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
- goto IL_C0;
- }
- }
- else
- {
- textFormatFlags = TextFormatFlags.VerticalCenter;
- if (rightToLeft)
- {
- textFormatFlags |= TextFormatFlags.Right;
- goto IL_C0;
- }
- goto IL_C0;
- }
- break;
- }
- }
- else
- {
- if (alignment <= DataGridViewContentAlignment.BottomLeft)
- {
- if (alignment != DataGridViewContentAlignment.MiddleRight)
- {
- if (alignment == DataGridViewContentAlignment.BottomLeft)
- {
- textFormatFlags = TextFormatFlags.Bottom;
- if (rightToLeft)
- {
- textFormatFlags |= TextFormatFlags.Right;
- goto IL_C0;
- }
- goto IL_C0;
- }
- }
- else
- {
- textFormatFlags = TextFormatFlags.VerticalCenter;
- if (rightToLeft)
- {
- goto IL_C0;
- }
- textFormatFlags |= TextFormatFlags.Right;
- goto IL_C0;
- }
- }
- else
- {
- if (alignment == DataGridViewContentAlignment.BottomCenter)
- {
- textFormatFlags = (TextFormatFlags.Bottom | TextFormatFlags.HorizontalCenter);
- goto IL_C0;
- }
- if (alignment == DataGridViewContentAlignment.BottomRight)
- {
- textFormatFlags = TextFormatFlags.Bottom;
- if (rightToLeft)
- {
- goto IL_C0;
- }
- textFormatFlags |= TextFormatFlags.Right;
- goto IL_C0;
- }
- }
- }
- textFormatFlags = (TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
- IL_C0:
- if (wrapMode == DataGridViewTriState.False)
- {
- textFormatFlags |= TextFormatFlags.SingleLine;
- }
- else
- {
- textFormatFlags |= TextFormatFlags.WordBreak;
- }
- textFormatFlags |= TextFormatFlags.NoPrefix;
- textFormatFlags |= TextFormatFlags.PreserveGraphicsClipping;
- if (rightToLeft)
- {
- textFormatFlags |= TextFormatFlags.RightToLeft;
- }
- return textFormatFlags;
- }
- /// <summary>
- /// 画字符串(合并单元格 周兴 2015-12-6 增加)
- /// </summary>
- /// <param name="e"></param>
- /// <param name="cellwidth"></param>
- /// <param name="UpRows"></param>
- /// <param name="DownRows"></param>
- /// <param name="count"></param>
- private void PaintingFont(System.Windows.Forms.DataGridViewCellPaintingEventArgs e, int cellwidth, int UpRows, int DownRows, int count)
- {
- SolidBrush fontBrush = new SolidBrush(e.CellStyle.ForeColor);
- int fontheight = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Height;
- int fontwidth = (int)e.Graphics.MeasureString(e.Value.ToString(), e.CellStyle.Font).Width;
- int cellheight = e.CellBounds.Height;
- if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomCenter)
- {
- e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y + cellheight * DownRows - fontheight);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomLeft)
- {
- e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y + cellheight * DownRows - fontheight);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.BottomRight)
- {
- e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y + cellheight * DownRows - fontheight);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleCenter)
- {
- e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleLeft)
- {
- e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.MiddleRight)
- {
- e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopCenter)
- {
- e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1));
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopLeft)
- {
- e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X, e.CellBounds.Y - cellheight * (UpRows - 1));
- }
- else if (e.CellStyle.Alignment == DataGridViewContentAlignment.TopRight)
- {
- e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X + cellwidth - fontwidth, e.CellBounds.Y - cellheight * (UpRows - 1));
- }
- else
- {
- e.Graphics.DrawString(e.FormattedValue + "", e.CellStyle.Font, fontBrush, e.CellBounds.X + (cellwidth - fontwidth) / 2, e.CellBounds.Y - cellheight * (UpRows - 1) + (cellheight * count - fontheight) / 2);
- }
- }
- #endregion
- #region 受保护的方法/函数
- protected override void OnColumnDisplayIndexChanged(DataGridViewColumnEventArgs e)
- {
- try
- {
- if (_isOpenTotalRow && !IsClickF12)
- {
- _columnInfos = this.GetDataGridViewColumnInfos();
- if (_columnInfos != null)
- {
- for (int i = 0; i < _columnInfos.Length; i++)
- {
- if (_columnInfos[i].Visible)
- {
- NewText(_columnInfos[i].DataPropertyName, i);
- }
- }
- CountTotalRow();
- }
- base.OnColumnDisplayIndexChanged(e);
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- protected override bool ProcessDialogKey(Keys keyData)
- {
- if (keyData == Keys.Enter)
- {
- return this.ProcessRightKey(keyData);
- }
- return base.ProcessDialogKey(keyData);
- }
- public new bool ProcessRightKey(Keys keyData)
- {
- if (keyData == Keys.Enter)
- {
- if (!IsProcessRightFlag || this.CurrentCell == null)
- {
- return false;
- }
- int rowIndex = this.CurrentCell.RowIndex;
- int columnIndex = this.CurrentCell.ColumnIndex;
- string columnName = this.Columns[columnIndex].Name;
- // 选择商品时控制鼠标的行为
- if ((columnName.Contains("Code") || columnName.Contains("OnlyCode"))
- && !string.IsNullOrEmpty(this.CurrentRow.Cells[columnName].EditedFormattedValue + "")
- && !this.CurrentRow.Cells[columnName].EditedFormattedValue.ToString()
- .Equals(this.CurrentRow.Cells[columnName].Value))
- {
- base.ProcessRightKey(keyData);
- }
- // 如果是数值类型,数值合法时才跳到下一个可输入单元格
- if (this.CurrentCell != null && this.CurrentCell.ValueType != null
- && this.CurrentCell.ValueType.IsValueType
- && this.CurrentCell.EditType != null
- && "DataGridViewTextBoxEditingControl".Equals(this.CurrentCell.EditType.Name))
- {
- decimal temp = -1;
- bool flag = decimal.TryParse(this.CurrentRow.Cells[columnName].EditedFormattedValue + "", out temp);
- // 说明有非数字
- if (!flag)
- {
- return true;
- }
- }
- DataGridViewColumnInfo[] columnInfo = this.GetDataGridViewColumnInfos();
- if (columnInfo != null && columnInfo.Length > 0)
- {
- for (int i = rowIndex; i < this.Rows.Count; i++)
- {
- bool flag = false;
- for (int j = 0; j < columnInfo.Length; j++)
- {
- if (i == rowIndex)
- {
- if (!flag && !columnName.Equals(columnInfo[j].ColumnName))
- {
- continue;
- }
- else
- {
- if (!flag)
- {
- j += 1;
- }
- flag = true;
- }
- }
- if (columnInfo.Length > j && !this.Rows[i].Cells[columnInfo[j].ColumnName].ReadOnly
- && this.Rows[i].Cells[columnInfo[j].ColumnName].Visible)
- {
- //this.CurrentCell = this.Rows[i].Cells[columnInfo[j].ColumnName];
- this.Rows[i].Cells[columnInfo[j].ColumnName].Selected = true;
- return true;
- }
- }
- }
- }
- //base.ProcessRightKey(keyData);
- // 如果datagridview只读,按回车就会跳到下一行
- //if (!isEnterKey && this.ReadOnly)
- //{
- // if (this.CurrentCell.RowIndex < this.Rows.Count - 1)
- // {
- // this.CurrentCell = this.Rows[this.CurrentCell.RowIndex + 1].Cells[0];
- // }
- //}
- }
- return true;
- }
- protected override bool ProcessDataGridViewKey(KeyEventArgs e)
- {
- if (e.KeyCode == Keys.Enter)
- {
- //isEnterKey = true;
- return this.ProcessRightKey(e.KeyData);
- }
- return base.ProcessDataGridViewKey(e);
- }
- protected override void OnCellEnter(DataGridViewCellEventArgs e)
- {
- base.OnCellEnter(e);
- }
- protected override void OnMouseUp(MouseEventArgs e)
- {
- // used to keep extra mouse moves from selecting more rows when collapsing
- base.OnMouseUp(e);
- this._inExpandCollapseMouseCapture = false;
- }
- protected override void OnMouseMove(MouseEventArgs e)
- {
- // while we are expanding and collapsing a node mouse moves are
- // supressed to keep selections from being messed up.
- if (!this._inExpandCollapseMouseCapture)
- base.OnMouseMove(e);
- }
- protected virtual void SetBackColorCell(int viewRowIndex, int viewColumnIndex)
- {
- if (!this.Visible)
- {
- return;
- }
- if (CellBackColorFlag == CellBackColorFlags.None)
- {
- return;
- }
- if (viewRowIndex < 0)
- {
- for (int i = 0; i < this.Rows.Count; i++)
- {
- SetBackColorCell(i, viewColumnIndex);
- }
- }
- else if (viewColumnIndex < 0)
- {
- for (int i = 0; i < this.Columns.Count; i++)
- {
- SetBackColorCell(viewRowIndex, i);
- }
- }
- else if (0 <= viewRowIndex && 0 <= viewColumnIndex)
- {
- DataGridViewCell cell = this.Rows[viewRowIndex].Cells[viewColumnIndex];
- if (cell == null)
- {
- return;
- }
- if (this.ReadOnly || this.Rows[viewRowIndex].ReadOnly ||
- this.Columns[viewColumnIndex].ReadOnly ||
- this.Rows[viewRowIndex].Cells[viewColumnIndex].ReadOnly)
- {
- if (this.CellBackColorReadOnly != Color.Transparent &&
- (this.CellBackColorFlag &
- CellBackColorFlags.ReadOnlyBackColor) != 0)
- {
- cell.Style.BackColor = this.CellBackColorReadOnly;
- return;
- }
- }
- if (CurrentDataTable != null)
- {
- if ((CellBackColorFlag & CellBackColorFlags.ChangesBackColor) != 0)
- {
- DataRowView dataRowView = this.GetDataRowView(viewRowIndex);
- if (dataRowView != null)
- {
- switch (dataRowView.Row.RowState)
- {
- case DataRowState.Added:
- cell.Style.BackColor = CellBackColorAdded;
- return;
- case DataRowState.Modified:
- string dataPropertyName =
- this.Columns[viewColumnIndex].DataPropertyName;
- if (string.IsNullOrEmpty(dataPropertyName))
- {
- break;
- }
- object valueOriginal =
- dataRowView.Row[dataPropertyName, DataRowVersion.Original];
- object valueCurrent =
- dataRowView.Row[dataPropertyName, DataRowVersion.Current];
- if (!valueOriginal.Equals(valueCurrent))
- {
- if (valueOriginal.Equals(DBNull.Value) &&
- valueCurrent.Equals(string.Empty) ||
- valueCurrent.Equals(DBNull.Value) &&
- valueOriginal.Equals(string.Empty))
- {
- break;
- }
- cell.Style.BackColor = CellBackColorModified;
- return;
- }
- break;
- case DataRowState.Deleted:
- cell.Style.BackColor = CellBackColorDeleted;
- return;
- default:
- break;
- }
- }
- }
- }
- if (this.CellBackColorNochanged != Color.Transparent &&
- (cell.Style.BackColor != this.CellBackColorNochanged))
- {
- cell.Style.BackColor = this.CellBackColorNochanged;
- }
- }
- }
- protected void DispRowCount()
- {
- if (IsDispRowCount)
- {
- Graphics graphics = this.CreateGraphics();
- OnPaint(new PaintEventArgs(graphics, new Rectangle(new Point(0, 0),
- this.TopLeftHeaderCell.Size)));
- graphics.Dispose();
- }
- }
- protected void OnCsvCoverting(CsvConvertingEventArgs e)
- {
- if (CsvConverting != null)
- {
- CsvConverting(this, e);
- }
- }
- #region 树形结构
- public event ExpandingEventHandler NodeExpanding;
- public event ExpandedEventHandler NodeExpanded;
- public event CollapsingEventHandler NodeCollapsing;
- public event CollapsedEventHandler NodeCollapsed;
- protected virtual void OnNodeExpanding(ExpandingEventArgs e)
- {
- if (this.NodeExpanding != null)
- {
- NodeExpanding(this, e);
- }
- }
- protected virtual void OnNodeExpanded(ExpandedEventArgs e)
- {
- if (this.NodeExpanded != null)
- {
- NodeExpanded(this, e);
- }
- }
- protected virtual void OnNodeCollapsing(CollapsingEventArgs e)
- {
- if (this.NodeCollapsing != null)
- {
- NodeCollapsing(this, e);
- }
- }
- protected virtual void OnNodeCollapsed(CollapsedEventArgs e)
- {
- if (this.NodeCollapsed != null)
- {
- NodeCollapsed(this, e);
- }
- }
- #endregion
- #endregion
- #region 重写方法
- protected override bool SetCurrentCellAddressCore(int columnIndex, int rowIndex, bool setAnchorCellAddress, bool validateCurrentCell, bool throughMouseClick)
- {
- try
- {
- return base.SetCurrentCellAddressCore(columnIndex, rowIndex, setAnchorCellAddress, validateCurrentCell, throughMouseClick);
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- private bool _isFlag = false;
- protected override void OnCellValueChanged(DataGridViewCellEventArgs e)
- {
- if (e.ColumnIndex >= 0 && e.RowIndex >= 0 && !_isFlag)
- {
- string value = this.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue + "";
- if (!string.IsNullOrEmpty(value))
- {
- decimal valueDec = 0;
- string format = this.Columns[e.ColumnIndex].DefaultCellStyle.Format;
- bool flag = decimal.TryParse(value + "", out valueDec);
- if (flag && format.IndexOf("F") >= 0)
- {
- _isFlag = true;
- this.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = valueDec.ToString(format);
- _isFlag = false;
- }
- }
- }
- base.OnCellValueChanged(e);
- }
- protected override void OnSelectionChanged(EventArgs e)
- {
- try
- {
- base.OnSelectionChanged(e);
- // 开合并行之后,在切换行处理
- if (IsOpenMergeCellFlag && !string.IsNullOrEmpty(MergeOnlyColumn) &&
- MergeColumnNames != null && MergeColumnNames.Count > 0 &&
- this.Columns.Contains(MergeOnlyColumn) && this.CurrentCell != null
- && (string.IsNullOrEmpty(this.Tag + "") || Convert.ToBoolean(this.Tag)))
- {
- Color color;
- // 先清空颜色
- for (int i = 0; i < this.Rows.Count; i++)
- {
- if (string.IsNullOrEmpty(this.Rows[i].Cells[MergeOnlyColumn].Tag + ""))
- {
- color = Color.White;
- }
- else
- {
- color = ColorTranslator.FromHtml(this.Rows[i].Cells[MergeOnlyColumn].Tag + "");
- }
- for (int j = 0; j < this.Columns.Count; j++)
- {
- if (this.Rows[i].Cells[j].Style.BackColor == ColorTranslator.FromHtml(Constant.COLOR_RED))
- {
- this.Rows[i].Cells[j].Style.BackColor = color;
- this.Rows[i].Cells[j].Style.ForeColor = Color.Black;
- }
- }
- }
- // 向上找 ,如果有,就把背景颜色修改为选中
- string onlyColumnC = this.Rows[this.CurrentCell.RowIndex].Cells[MergeOnlyColumn].Value + "";
- string onlyDetailColumnC = string.Empty;
- if (!string.IsNullOrEmpty(MergeDetailOnlyColumn))
- {
- onlyDetailColumnC = this.Rows[this.CurrentCell.RowIndex].Cells[MergeDetailOnlyColumn].Value + "";
- }
- string onlyDDetailColumnC = string.Empty;
- if (!string.IsNullOrEmpty(MergeDDetailOnlyColumn))
- {
- onlyDDetailColumnC = this.Rows[this.CurrentCell.RowIndex].Cells[MergeDDetailOnlyColumn].Value + "";
- }
- List<string> tempColumns = new List<string>();
- if (MergeDDetailColumnNames != null && MergeDDetailColumnNames.Count > 0)
- {
- tempColumns.AddRange(MergeDDetailColumnNames.ToArray());
- }
- if (MergeDetailColumnNames != null && MergeDetailColumnNames.Count > 0)
- {
- tempColumns.AddRange(MergeDetailColumnNames.ToArray());
- }
- if (this.CurrentCell.RowIndex >= 1)
- {
- for (int i = this.CurrentCell.RowIndex - 1; i >= 0; i--)
- {
- if (!string.IsNullOrEmpty(onlyDDetailColumnC) && onlyDDetailColumnC.Equals(this.Rows[i].Cells[MergeDDetailOnlyColumn].Value + ""))
- {
- if (MergeDDetailColumnNames != null)
- {
- for (int j = 0; j < MergeDDetailColumnNames.Count; j++)
- {
- if (this.Columns.Contains(MergeDDetailColumnNames[j]))
- {
- this.Rows[i].Cells[MergeDDetailColumnNames[j]].Style.BackColor = ColorTranslator.FromHtml(Constant.COLOR_RED);
- this.Rows[i].Cells[MergeDDetailColumnNames[j]].Style.ForeColor = Color.White;
- }
- }
- }
- }
- else if (!string.IsNullOrEmpty(onlyDetailColumnC) && onlyDetailColumnC.Equals(this.Rows[i].Cells[MergeDetailOnlyColumn].Value + ""))
- {
- if (MergeDetailColumnNames != null)
- {
- for (int j = 0; j < MergeDetailColumnNames.Count; j++)
- {
- if (this.Columns.Contains(MergeDetailColumnNames[j]))
- {
- this.Rows[i].Cells[MergeDetailColumnNames[j]].Style.BackColor = ColorTranslator.FromHtml(Constant.COLOR_RED);
- this.Rows[i].Cells[MergeDetailColumnNames[j]].Style.ForeColor = Color.White;
- }
- }
- }
- }
- else if (!string.IsNullOrEmpty(onlyColumnC) && onlyColumnC.Equals(this.Rows[i].Cells[MergeOnlyColumn].Value + ""))
- {
- for (int j = 0; j < MergeColumnNames.Count; j++)
- {
- if (this.Columns.Contains(MergeColumnNames[j]) && !tempColumns.Contains(MergeColumnNames[j]))
- {
- this.Rows[i].Cells[MergeColumnNames[j]].Style.BackColor = ColorTranslator.FromHtml(Constant.COLOR_RED);
- this.Rows[i].Cells[MergeColumnNames[j]].Style.ForeColor = Color.White;
- }
- }
- }
- }
- }
- // 向下 ,如果有,就把背景颜色修改为选中
- if (this.CurrentCell.RowIndex <= this.Rows.Count - 2)
- {
- for (int i = this.CurrentCell.RowIndex + 1; i <= this.Rows.Count - 1; i++)
- {
- if (!string.IsNullOrEmpty(onlyDDetailColumnC) && onlyDDetailColumnC.Equals(this.Rows[i].Cells[MergeDDetailOnlyColumn].Value + ""))
- {
- if (MergeDDetailColumnNames != null)
- {
- for (int j = 0; j < MergeDDetailColumnNames.Count; j++)
- {
- if (this.Columns.Contains(MergeDDetailColumnNames[j]))
- {
- this.Rows[i].Cells[MergeDDetailColumnNames[j]].Style.BackColor = ColorTranslator.FromHtml(Constant.COLOR_RED);
- this.Rows[i].Cells[MergeDDetailColumnNames[j]].Style.ForeColor = Color.White;
- }
- }
- }
- }
- else if (!string.IsNullOrEmpty(onlyDetailColumnC) && onlyDetailColumnC.Equals(this.Rows[i].Cells[MergeDetailOnlyColumn].Value + ""))
- {
- if (MergeDetailColumnNames != null)
- {
- for (int j = 0; j < MergeDetailColumnNames.Count; j++)
- {
- if (this.Columns.Contains(MergeDetailColumnNames[j]))
- {
- this.Rows[i].Cells[MergeDetailColumnNames[j]].Style.BackColor = ColorTranslator.FromHtml(Constant.COLOR_RED);
- this.Rows[i].Cells[MergeDetailColumnNames[j]].Style.ForeColor = Color.White;
- }
- }
- }
- }
- else if (!string.IsNullOrEmpty(onlyColumnC) && onlyColumnC.Equals(this.Rows[i].Cells[MergeOnlyColumn].Value + ""))
- {
- for (int j = 0; j < MergeColumnNames.Count; j++)
- {
- if (this.Columns.Contains(MergeColumnNames[j]) && !tempColumns.Contains(MergeColumnNames[j]))
- {
- this.Rows[i].Cells[MergeColumnNames[j]].Style.BackColor = ColorTranslator.FromHtml(Constant.COLOR_RED);
- this.Rows[i].Cells[MergeColumnNames[j]].Style.ForeColor = Color.White;
- }
- }
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- protected override void OnHandleCreated(EventArgs e)
- {
- base.OnHandleCreated(e);
- // this control is used to temporarly hide the vertical scroll bar
- hideScrollBarControl = new Control();
- hideScrollBarControl.Visible = false;
- hideScrollBarControl.Enabled = false;
- hideScrollBarControl.TabStop = false;
- // control is disposed automatically when the grid is disposed
- this.Controls.Add(hideScrollBarControl);
- }
- protected override void OnRowEnter(DataGridViewCellEventArgs e)
- {
- // ensure full row select
- base.OnRowEnter(e);
- if (this.SelectionMode == DataGridViewSelectionMode.CellSelect ||
- (this.SelectionMode == DataGridViewSelectionMode.FullRowSelect &&
- base.Rows[e.RowIndex].Selected == false))
- {
- this.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
- base.Rows[e.RowIndex].Selected = true;
- }
- }
- private void LockVerticalScrollBarUpdate(bool lockUpdate/*, bool delayed*/)
- {
- // Temporarly hide/show the vertical scroll bar by changing its parent
- if (!this._inExpandCollapse)
- {
- if (lockUpdate)
- {
- this.VerticalScrollBar.Parent = hideScrollBarControl;
- }
- else
- {
- this.VerticalScrollBar.Parent = this;
- }
- }
- }
- protected override void OnPaint(PaintEventArgs e)
- {
- try
- {
- try
- {
- base.OnPaint(e);
- }
- catch (Exception ex)
- {
- ex.ToString();
- }
- // 头部分的重绘
- if (this.HitTest(e.ClipRectangle.Left + 1, e.ClipRectangle.Top + 1).Type == DataGridViewHitTestType.TopLeftHeader)
- {
- // 属性设置需要显示总行数
- if (IsDispRowCount)
- {
- // 当前选择行的Index
- int currentIndex = 0;
- if (this.CurrentRow == null)
- {
- return;
- }
- else
- {
- currentIndex = this.CurrentRow.Index;
- }
- // 内容的绘制
- Rectangle rect = new Rectangle(0, 0, this.RowHeadersWidth - 4, this.ColumnHeadersHeight);
- int rowCount = this.RowCount;
- if (this.AllowUserToAddRows)
- {
- rowCount--;
- }
- string comment = string.Format("{0}/{1}",
- currentIndex + 1,
- rowCount
- );
- TextRenderer.DrawText(
- e.Graphics,
- comment, this.ColumnHeadersDefaultCellStyle.Font,
- rect, this.ColumnHeadersDefaultCellStyle.ForeColor,
- TextFormatFlags.VerticalCenter | TextFormatFlags.Right
- );
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- //Debug.Assert(false, "Error", ex.Message);
- }
- }
- /// <summary>
- /// 滚动
- /// </summary>
- /// <param name="e"></param>
- protected override void OnScroll(ScrollEventArgs e)
- {
- try
- {
- bool scrollDirection = (e.ScrollOrientation == ScrollOrientation.HorizontalScroll);
- base.OnScroll(e);
- if (_isOpenTotalRow)
- {
- SetTxtTop();
- SetTxtLeft();
- }
- if (RefreshAtHscroll && scrollDirection)
- {
- this.Refresh();
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- protected override void OnRowHeadersWidthChanged(EventArgs e)
- {
- if (_isOpenTotalRow && _columnInfos != null)
- {
- if (findTextBox("txt" + this.Name) == null)
- {
- return;
- }
- findTextBox("txt" + this.Name).Width = this.RowHeadersWidth;
- for (int i = 0; i < _columnInfos.Length; i++)
- {
- if (_columnInfos[i].Visible && findTextBox("txt" + _columnInfos[i].DataPropertyName) != null)
- {
- findTextBox("txt" + _columnInfos[i].DataPropertyName).Left = getLeft(_columnInfos[i].DataPropertyName, i);
- }
- }
- }
- base.OnRowHeadersWidthChanged(e);
- }
- /// <summary>
- /// 列宽度改变时的重写
- /// </summary>
- /// <param name="e"></param>
- protected override void OnColumnWidthChanged(DataGridViewColumnEventArgs e)
- {
- if (_isOpenTotalRow && _columnInfos != null && !IsAutoResizeColumns)
- {
- _columnInfos = GetDataGridViewColumnInfos();
- //bool flag = false;
- //for (int i = 0; i < _columnInfos.Length; i++)
- //{
- // if (_columnInfos[i].DataPropertyName.Equals(e.Column.DataPropertyName))
- // {
- // if (findTextBox("txt" + _columnInfos[i].DataPropertyName) == null)
- // {
- // return;
- // }
- // findTextBox("txt" + _columnInfos[i].DataPropertyName).Width = e.Column.Width;
- // flag = true;
- // }
- // if (flag && _columnInfos[i].Visible)
- // {
- // findTextBox("txt" + _columnInfos[i].DataPropertyName).Left = getLeft(_columnInfos[i].DataPropertyName, i);
- // }
- //}
- for (int i = 0; i < _columnInfos.Length; i++)
- {
- if (_columnInfos[i].Visible)
- {
- NewText(_columnInfos[i].DataPropertyName, i);
- }
- }
- CountTotalRow();
- }
- Graphics g = Graphics.FromHwnd(this.Handle);
- float uwh = g.MeasureString(e.Column.HeaderText, this.Font).Width;
- if (uwh >= e.Column.Width)
- {
- e.Column.Width = Convert.ToInt16(uwh);
- }
- base.OnColumnWidthChanged(e);
- if (RefreshAtHscroll)
- {
- this.Refresh();
- }
- }
- protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
- {
- if (e.ColumnIndex < 0 || _columnDeep == 1)
- {
- // 周兴 2015-12-6 增加 合并单元格
- if (e.RowIndex > -1 && e.ColumnIndex > -1)
- {
- DrawCell(e);
- }
- base.OnCellPainting(e);
- return;
- }
- if (e.RowIndex == -1)
- {
- object[] colList = ColumnList.ToArray();
- if (e.ColumnIndex >= colList.Length)
- {
- e.Handled = true;
- return;
- }
- PaintUnitHeader((TreeNode)colList[e.ColumnIndex], e, _columnDeep);
- e.Handled = true;
- }
- else
- {
- // 周兴 2015-12-6 增加 合并单元格
- if (e.RowIndex > -1 && e.ColumnIndex > -1)
- {
- DrawCell(e);
- }
- base.OnCellPainting(e);
- }
- }
- protected override void OnRowsAdded(DataGridViewRowsAddedEventArgs e)
- {
- if (_isOpenTotalRow && IsAutoCountSum)
- {
- CountTotalRow();
- }
- base.OnRowsAdded(e);
- // Notify the row when it is added to the base grid
- int count = e.RowCount - 1;
- TreeGridNode row;
- while (count >= 0)
- {
- row = base.Rows[e.RowIndex + count] as TreeGridNode;
- if (row != null)
- {
- row.Sited();
- }
- count--;
- }
- }
- internal protected void UnSiteAll()
- {
- this.UnSiteNode(this._root);
- }
- internal protected virtual void UnSiteNode(TreeGridNode node)
- {
- if (node != null && (node.IsSited || node.IsRoot))
- {
- // remove child rows first
- foreach (TreeGridNode childNode in node.Nodes)
- {
- this.UnSiteNode(childNode);
- }
- // now remove this row except for the root
- if (!node.IsRoot)
- {
- // zx 解决加载树形结构页面关闭时的bug
- try
- {
- base.Rows.Remove(node);
- // Row isn't sited in the grid anymore after remove. Note that we cannot
- // Use the RowRemoved event since we cannot map from the row index to
- // the index of the expandable row/node.
- node.UnSited();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- }
- }
- internal protected virtual bool CollapseNode(TreeGridNode node)
- {
- if (node.IsExpanded)
- {
- CollapsingEventArgs exp = new CollapsingEventArgs(node);
- this.OnNodeCollapsing(exp);
- if (!exp.Cancel)
- {
- this.LockVerticalScrollBarUpdate(true);
- this.SuspendLayout();
- _inExpandCollapse = true;
- node.IsExpanded = false;
- foreach (TreeGridNode childNode in node.Nodes)
- {
- Debug.Assert(childNode.RowIndex != -1, "Row is NOT in the grid.");
- this.UnSiteNode(childNode);
- }
- CollapsedEventArgs exped = new CollapsedEventArgs(node);
- this.OnNodeCollapsed(exped);
- //TODO: Convert this to a specific NodeCell property
- _inExpandCollapse = false;
- this.LockVerticalScrollBarUpdate(false);
- this.ResumeLayout(true);
- this.InvalidateCell(node.Cells[0]);
- }
- return !exp.Cancel;
- }
- else
- {
- // row isn't expanded, so we didn't do anything.
- return false;
- }
- }
- internal protected virtual void SiteNode(TreeGridNode node)
- {
- //TODO: Raise exception if parent node is not the root or is not sited.
- int rowIndex = -1;
- TreeGridNode currentRow;
- node._grid = this;
- if (node.Parent != null && node.Parent.IsRoot == false)
- {
- // row is a child
- Debug.Assert(node.Parent != null && node.Parent.IsExpanded == true);
- if (node.Index > 0)
- {
- currentRow = node.Parent.Nodes[node.Index - 1];
- }
- else
- {
- currentRow = node.Parent;
- }
- }
- else
- {
- // row is being added to the root
- if (node.Index > 0)
- {
- currentRow = node.Parent.Nodes[node.Index - 1];
- }
- else
- {
- currentRow = null;
- }
- }
- if (currentRow != null)
- {
- while (currentRow.Level >= node.Level)
- {
- if (currentRow.RowIndex < base.Rows.Count - 1)
- {
- currentRow = base.Rows[currentRow.RowIndex + 1] as TreeGridNode;
- Debug.Assert(currentRow != null);
- }
- else
- // no more rows, site this node at the end.
- break;
- }
- if (currentRow == node.Parent)
- rowIndex = currentRow.RowIndex + 1;
- else if (currentRow.Level < node.Level)
- rowIndex = currentRow.RowIndex;
- else
- rowIndex = currentRow.RowIndex + 1;
- }
- else
- rowIndex = 0;
- Debug.Assert(rowIndex != -1);
- this.SiteNode(node, rowIndex);
- Debug.Assert(node.IsSited);
- node.IsExpanded = _isExpandAll;
- if (node.IsExpanded)
- {
- // add all child rows to display
- foreach (TreeGridNode childNode in node.Nodes)
- {
- //TODO: could use the more efficient SiteRow with index.
- this.SiteNode(childNode);
- }
- }
- }
- private bool _isExpandAll = false;
- /// <summary>
- /// 是否打开所有树形结构的节点
- /// </summary>
- public bool IsExpandAll
- {
- set
- {
- if (HasNode && !string.IsNullOrEmpty(NodeColumnName))
- {
- _isExpandAll = value;
- }
- }
- }
- protected override void OnColumnAdded(DataGridViewColumnEventArgs e)
- {
- if (typeof(TreeGridColumn).IsAssignableFrom(e.Column.GetType()))
- {
- if (_expandableColumn == null)
- {
- // identify the expanding column.
- _expandableColumn = (TreeGridColumn)e.Column;
- }
- else
- {
- // this.Columns.Remove(e.Column);
- //throw new InvalidOperationException("Only one TreeGridColumn per TreeGridView is supported.");
- }
- }
- // Expandable Grid doesn't support sorting. This is just a limitation of the sample.
- //e.Column.SortMode = DataGridViewColumnSortMode.Automatic;
- base.OnColumnAdded(e);
- e.Column.HeaderCell.Style.WrapMode = DataGridViewTriState.False;
- }
- internal protected virtual void SiteNode(TreeGridNode node, int index)
- {
- if (index < base.Rows.Count)
- {
- base.Rows.Insert(index, node);
- }
- else
- {
- // for the last item.
- base.Rows.Add(node);
- }
- }
- internal protected virtual bool ExpandNode(TreeGridNode node)
- {
- if (!node.IsExpanded || this._virtualNodes)
- {
- ExpandingEventArgs exp = new ExpandingEventArgs(node);
- this.OnNodeExpanding(exp);
- if (!exp.Cancel)
- {
- this.LockVerticalScrollBarUpdate(true);
- this.SuspendLayout();
- _inExpandCollapse = true;
- node.IsExpanded = true;
- //TODO Convert this to a InsertRange
- foreach (TreeGridNode childNode in node.Nodes)
- {
- Debug.Assert(childNode.RowIndex == -1, "Row is already in the grid.");
- this.SiteNode(childNode);
- //this.BaseRows.Insert(rowIndex + 1, childRow);
- //TODO : remove -- just a test.
- //childNode.Cells[0].Value = "child";
- }
- ExpandedEventArgs exped = new ExpandedEventArgs(node);
- this.OnNodeExpanded(exped);
- //TODO: Convert this to a specific NodeCell property
- _inExpandCollapse = false;
- this.LockVerticalScrollBarUpdate(false);
- this.ResumeLayout(true);
- this.InvalidateCell(node.Cells[0]);
- }
- return !exp.Cancel;
- }
- else
- {
- // row is already expanded, so we didn't do anything.
- return false;
- }
- }
- private void InitNode(DataTable dataTable, TreeGridNode node,
- SortedList<int, string> sortedlist, DataRow[] dataRows)
- {
- DataRow[] dataRowsTmp = null;
- TreeGridNode nodeTmp = null;
- for (int i = 0; i < dataRows.Length; i++)
- {
- nodeTmp = node.Nodes.Add(dataRows[i], dataTable.Columns, this.Columns, sortedlist, out sortedlist);
- dataRowsTmp = dataTable.Select(" ParentID = " + dataRows[i][NodeColumnName]);
- InitNode(dataTable, nodeTmp, sortedlist, dataRowsTmp);
- }
- }
- #endregion
- #region 事件
- #region 单元格事件
- private void dkDataGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
- {
- if (this.IsHandleCreated)
- {
- DispRowCount();
- }
- }
- private void dkDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
- {
- // 清除错误显示
- }
- private void dkDataGridView_CellValidated(object sender, DataGridViewCellEventArgs e)
- {
- DataTable dtblDataTable = GetDataTable();
- if (dtblDataTable != null && this.IsCurrentRowDirty)
- {
- DataGridView dataGridView = (DataGridView)sender;
- DataColumn dataColumn =
- dtblDataTable.Columns[dataGridView.Columns[e.ColumnIndex].DataPropertyName];
- if (dataColumn != null)
- {
- if (!dataColumn.AllowDBNull)
- {
- if (dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == DBNull.Value)
- {
- if (dataColumn.DataType.Equals(typeof(string)))
- {
- dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = string.Empty;
- }
- }
- }
- }
- }
- }
- private bool IsSelectSameCell(int selectCellRowIndex, int selectCellColumnIndex)
- {
- if ((selectCellRowIndex == _selectCellRowCol[0]) && (selectCellColumnIndex == _selectCellRowCol[1]))
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- private void SetMnuFrozenText(int intRowIndex, int intColumnIndex)
- {
- bool isSelectSameCell = true;
- isSelectSameCell = IsSelectSameCell(intRowIndex, intColumnIndex);
- if (isSelectSameCell && _isFrozen)
- {
- _mnuFrozen.Text = ControlsTips.DK_DataGridView_UnFrozen;
- }
- else
- {
- _mnuFrozen.Text = ControlsTips.DK_DataGridView_Frozen;
- }
- }
- private void SetGridViewColumnHeaderMenu()
- {
- _ctxColumnHeader.Items.Clear();
- if (this.ContextMenuVisible != ContextMenuVisibleFlags.None)
- {
- AddToolStripSeparator(_ctxColumnHeader);
- _ctxColumnHeader.Items.Add(this._mnuFrozen);
- }
- if ((this.ContextMenuVisible & ContextMenuVisibleFlags.Refine) ==
- ContextMenuVisibleFlags.Refine)
- {
- AddToolStripSeparator(_ctxColumnHeader);
- _ctxColumnHeader.Items.Add(this._mnuRefine);
- _ctxColumnHeader.Items.Add(this._mnuUnfilter);
- }
- if (IsExportFlag && (this.ContextMenuVisible & ContextMenuVisibleFlags.FileOut) ==
- ContextMenuVisibleFlags.FileOut)
- {
- AddToolStripSeparator(_ctxColumnHeader);
- _ctxColumnHeader.Items.Add(this._mnuOutputFile);
- _ctxColumnHeader.Items.Add(this._mnuOutputFileXls);
- }
- }
- private void SetGridViewCellMenu(DataGridViewRow gridViewRow)
- {
- _ctxCell.Items.Clear();
- // 右键菜单的Item设定
- if (this.ContextMenuVisible != ContextMenuVisibleFlags.None)
- {
- AddToolStripSeparator(_ctxCell);
- _ctxCell.Items.Add(this._mnuFrozen);
- }
- if (!gridViewRow.IsNewRow)
- {
- // 不存在新建行的情况
- if ((this.ContextMenuVisible & ContextMenuVisibleFlags.Refine) ==
- ContextMenuVisibleFlags.Refine)
- {
- AddToolStripSeparator(_ctxCell);
- _ctxCell.Items.Add(this._mnuRefine);
- _ctxCell.Items.Add(this._mnuFilter);
- _ctxCell.Items.Add(this._mnuFilterExcept);
- _ctxCell.Items.Add(this._mnuUnfilter);
- }
- }
- else
- {
- // 新建行的情况
- if ((this.ContextMenuVisible & ContextMenuVisibleFlags.Refine) ==
- ContextMenuVisibleFlags.Refine)
- {
- AddToolStripSeparator(_ctxCell);
- _ctxCell.Items.Add(this._mnuRefine);
- _ctxCell.Items.Add(this._mnuUnfilter);
- }
- }
- if (IsExportFlag && (this.ContextMenuVisible & ContextMenuVisibleFlags.FileOut) ==
- ContextMenuVisibleFlags.FileOut)
- {
- AddToolStripSeparator(_ctxCell);
- _ctxCell.Items.Add(this._mnuOutputFile);
- _ctxCell.Items.Add(this._mnuOutputFileXls);
- }
- //if (IsPrintFlag && (this.ContextMenuVisible & ContextMenuVisibleFlags.Print) == ContextMenuVisibleFlags.Print)
- //{
- // AddToolStripSeparator(_ctxCell);
- // _ctxCell.Items.Add(this._mnuPrint);
- //}
- }
- private void DataGridViewMouseDownRight(DataGridView.HitTestInfo gridViewHitTestInfo, MouseEventArgs e)
- {
- try
- {
- // 如果是数值类型,数值合法时才跳到下一个可输入单元格
- if (this.CurrentCell != null && this.CurrentCell.ValueType != null
- && this.CurrentCell.ValueType.IsValueType
- && this.CurrentCell.EditType != null
- && "DataGridViewTextBoxEditingControl".Equals(this.CurrentCell.EditType.Name))
- {
- if ("int".Equals(this.CurrentCell.ValueType.Name.ToLower())
- || "decimal".Equals(this.CurrentCell.ValueType.Name.ToLower())
- || "double".Equals(this.CurrentCell.ValueType.Name.ToLower()))
- {
- string columnName = this.Columns[this.CurrentCell.ColumnIndex].Name;
- decimal temp = -1;
- bool flag = decimal.TryParse(this.CurrentRow.Cells[columnName].EditedFormattedValue + "", out temp);
- // 说明有非数字
- if (!flag)
- {
- return;
- }
- }
- }
- if (gridViewHitTestInfo.Type == DataGridViewHitTestType.ColumnHeader)
- {
- // 点击列头的情况下,设定右键菜单的Item
- SetGridViewColumnHeaderMenu();
- Point point = new Point(e.X, e.Y);
- point = this.PointToScreen(point);
- _ctxColumnHeader.Tag = gridViewHitTestInfo;
- _ctxColumnHeader.Show(point);
- _gridRowIndex = 0;
- _gridColumnindex = gridViewHitTestInfo.ColumnIndex;
- }
- else if (gridViewHitTestInfo.Type == DataGridViewHitTestType.Cell)
- {
- // 点击单元格的情况
- DataGridViewRow gridViewRow = this.Rows[gridViewHitTestInfo.RowIndex];
- int intSelRowsCount = this.SelectedRows.Count;
- if (gridViewRow != null)
- {
- if (_isShowDelete)
- {
- if (1 == intSelRowsCount)
- {
- _ctxCell.Items.Clear();
- // 设定右键菜单的Item
- if (this.ContextMenuVisible != ContextMenuVisibleFlags.None)
- {
- AddToolStripSeparator(_ctxCell);
- _ctxCell.Items.Add(this._mnuDelete);
- }
- Point point = new Point(e.X, e.Y);
- point = this.PointToScreen(point);
- _ctxCell.Tag = gridViewHitTestInfo;
- _ctxCell.Show(point);
- }
- }
- else
- {
- if (!_isCanDelete)
- {
- if (!gridViewRow.IsNewRow)
- {
- this.Tag = false;
- this.CurrentCell = gridViewRow.Cells[gridViewHitTestInfo.ColumnIndex];
- this.Tag = true;
- // 点击右键要调到相应的行去 周兴 2016-11-3 修改
- if (IsOpenMergeCellFlag )
- {
- this.OnSelectionChanged(e);
- }
- }
- // 设定右键菜单的Item
- SetGridViewCellMenu(gridViewRow);
- Point point = new Point(e.X, e.Y);
- point = this.PointToScreen(point);
- _ctxCell.Tag = gridViewHitTestInfo;
- _ctxCell.Show(point);
- _gridRowIndex = gridViewHitTestInfo.RowIndex;
- _gridColumnindex = gridViewHitTestInfo.ColumnIndex;
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- // todo 捕获之后不操作
- }
- }
- #endregion
- #region 行事件
- private void dkDataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
- {
- DataGridViewRow currentRow = ((DataGridView)sender).Rows[e.RowIndex];
- if (currentRow != null)
- {
- if (!currentRow.IsNewRow)
- {
- if (currentRow.ReadOnly != !_isAllowUserToModifyRows)
- {
- currentRow.ReadOnly = !_isAllowUserToModifyRows;
- }
- }
- }
- if (this.IsCurrentCellDirty)
- {
- this.NotifyCurrentCellDirty(false);
- }
- }
- private void Rows_CollectionChanged(object sender,
- System.ComponentModel.CollectionChangeEventArgs e)
- {
- switch (e.Action)
- {
- case System.ComponentModel.CollectionChangeAction.Refresh:
- if (this.Rows.Count > 0)
- {
- SetBackColorCell(-1, -1);
- }
- break;
- case System.ComponentModel.CollectionChangeAction.Add:
- break;
- case System.ComponentModel.CollectionChangeAction.Remove:
- break;
- }
- }
- private void dkDataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
- {
- SetBackColorCell(e.RowIndex, -1);
- }
- #endregion
- #region 鼠标、键盘事件
- private void dkDataGridView_MouseDown(object sender, MouseEventArgs e)
- {
- DataGridView.HitTestInfo gridViewHitTestInfo = this.HitTest(e.X, e.Y);
- if (gridViewHitTestInfo.Type == DataGridViewHitTestType.None)
- {
- if (this.IsClearSelected)
- {
- // 清除选择行
- this.ClearSelection();
- }
- this.labelHideFocus.Focus();
- if (MouseClickOnSpace != null)
- {
- MouseClickOnSpace(this, e);
- }
- return;
- }
- if ((e.Button & MouseButtons.Right) == MouseButtons.Right)
- {
- // 右键点击
- DataGridViewMouseDownRight(gridViewHitTestInfo, e);
- SetMnuFrozenText(gridViewHitTestInfo.RowIndex, gridViewHitTestInfo.ColumnIndex);
- }
- }
- /// <summary>
- /// 按下ESC键的处理
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void dkDataGridView_EscKeyDown(object sender, KeyEventArgs e)
- {
- if (e.KeyCode == Keys.Escape)
- {
- if (this.IsClearSelected)
- {
- this.ClearSelection();
- this.labelHideFocus.Focus();
- if (MouseClickOnSpace != null)
- {
- MouseClickOnSpace(this, e);
- }
- }
- }
- }
- private void AddToolStripSeparator(ContextMenuStrip contextMenuStrip)
- {
- if (contextMenuStrip.Items.Count == 0)
- {
- return;
- }
- if (contextMenuStrip.Items[contextMenuStrip.Items.Count - 1] is ToolStripSeparator)
- {
- return;
- }
- contextMenuStrip.Items.Add(new ToolStripSeparator());
- }
- private void dkDataGridView_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
- {
- ((DataGridView)sender).EndEdit();
- }
- #endregion
- #region 右键菜单事件
- private void mnuRefine_RefineTextFixed(object sender, EventArgs e)
- {
- if (string.IsNullOrEmpty(_mnuRefine.Text))
- {
- MessageBox.Show(ControlsTips.DK_DataGridView_RefineEmpty);
- }
- else
- {
- ToolStripItem toolStripItem = sender as ToolStripItem;
- if (toolStripItem == null)
- {
- return;
- }
- ContextMenuStrip contextMenuStrip = toolStripItem.Owner as ContextMenuStrip;
- if (contextMenuStrip == null)
- {
- return;
- }
- contextMenuStrip.Close();
- HitTestInfo info = (HitTestInfo)contextMenuStrip.Tag;
- this.Tag = false;
- this.FilterRow(info.ColumnIndex, FilterType.Like, _mnuRefine.Text);
- this.Tag = true;
- this.OnSelectionChanged(e);
- }
- }
- protected String ConvertRegularExpressionFilter(String sqlFilter)
- {
- if (String.IsNullOrEmpty(sqlFilter))
- {
- return sqlFilter;
- }
- if ("%".Equals(sqlFilter))
- {
- return ".";
- }
- Boolean isStartVague = (sqlFilter.Substring(0, 1) == "%");
- Boolean isEndVague = (sqlFilter.Substring(sqlFilter.Length - 1, 1) == "%");
- String escapedSqlFilter = sqlFilter.Substring((isStartVague) ? 1 : 0,
- sqlFilter.Length - ((isEndVague) ? 1 : 0) - ((isStartVague) ? 1 : 0));
- return String.Format("{0}{1}{2}", isStartVague ? String.Empty : "%",
- escapedSqlFilter, isEndVague ? String.Empty : "%");
- }
- private void mnuFilter_Click(object sender, EventArgs e)
- {
- this.Tag = false;
- this.FilterRow(FilterType.Equal);
- this.Tag = true;
- this.OnSelectionChanged(e);
- }
- private void mnuFilterExcept_Click(object sender, EventArgs e)
- {
- this.Tag = false;
- this.FilterRow(FilterType.NotEqual);
- this.Tag = true;
- this.OnSelectionChanged(e);
- }
- private void mnuUnfilter_Click(object sender, EventArgs e)
- {
- this.Tag = false;
- this.ResetFilter();
- this.Tag = true;
- this.OnSelectionChanged(e);
- }
- private void mnuOutputFile_Click(object sender, EventArgs e)
- {
- this.OutputFile();
- }
- private void mnuOutputFileXls_Click(object sender, EventArgs e)
- {
- this.OutputFileXls();
- }
- private void mnuFrozen_Click(object sender, EventArgs e)
- {
- this.Tag = false;
- this.SetFrozen();
- this.Tag = true;
- }
- private void mnuDelete_Click(object sender, EventArgs e)
- {
- if (RowsHeaderClick != null)
- {
- RowsHeaderClick(this, e);
- }
- }
- private void mnuPrint_Click(object sender, EventArgs e)
- {
- VBprinter.DGVprint dGVprint = new VBprinter.DGVprint();
- dGVprint.PrintType = VBprinter.DGVprint.mytype.GeneralPrint;//打印对齐
- dGVprint.Alignment = StringAlignment.Center; //表格居中
- dGVprint.MainTitle = this.Text;//主标题
- dGVprint.AutoFormat = false;//自动调整行宽
- dGVprint.IsShowUnvisibleColum = false;//是否显示隐藏列
- if (this.ColumnTreeView == null || this.ColumnTreeView.Length == 0)
- {
- dGVprint.Print(this, true, "");
- }
- else
- {
- dGVprint.Print(this, true, "", this.ColumnTreeView[0]);
- }
- }
- #endregion
- #region dkDataGridView事件
- private void dkDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
- {
- if (e.Context == DataGridViewDataErrorContexts.Commit)
- {
- e.Cancel = true;
- }
- }
- private void dkDataGridView_ReadOnlyChanged(object sender, EventArgs e)
- {
- SetBackColorCell(-1, -1);
- }
- private void dkDataGridView_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
- {
- if (e.KeyCode == Keys.Escape)
- {
- if (this.DataSource != null)
- {
- if (this.BindingContext[this.DataSource, this.DataMember].Count ==
- 1 && this.CurrentRow.IsNewRow)
- {
- this.BindingContext[this.DataSource, this.DataMember].RemoveAt(0);
- }
- }
- }
- }
- private void dkDataGridView_EditingControlShowing(object sender,
- DataGridViewEditingControlShowingEventArgs e)
- {
- if (this.EditingControl != null)
- {
- this.EditingControl.PreviewKeyDown -=
- new PreviewKeyDownEventHandler(EditingControl_PreviewKeyDown);
- this.EditingControl.PreviewKeyDown +=
- new PreviewKeyDownEventHandler(EditingControl_PreviewKeyDown);
- }
- }
- private void EditingControl_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
- {
- if (e.KeyCode == Keys.Escape)
- {
- if (this.DataSource != null)
- {
- if (this.BindingContext[this.DataSource, this.DataMember].Count ==
- 1 && this.CurrentRow.IsNewRow)
- {
- this.BindingContext[this.DataSource, this.DataMember].RemoveAt(0);
- }
- }
- }
- }
- #endregion
- #endregion
- #region 设计自动生成代码
- private void InitializeComponent()
- {
- this.components = new System.ComponentModel.Container();
- System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
- System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
- System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
- this._ctxColumnHeader = new System.Windows.Forms.ContextMenuStrip(this.components);
- this._ctxCell = new System.Windows.Forms.ContextMenuStrip(this.components);
- this.labelHideFocus = new System.Windows.Forms.Label();
- ((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
- this.SuspendLayout();
- //
- // _ctxColumnHeader
- //
- this._ctxColumnHeader.Name = "contextMenuStrip1";
- this._ctxColumnHeader.Size = new System.Drawing.Size(61, 4);
- //
- // _ctxCell
- //
- this._ctxCell.Name = "ctxCell";
- this._ctxCell.Size = new System.Drawing.Size(61, 4);
- //
- // labelHideFocus
- //
- this.labelHideFocus.AutoSize = true;
- this.labelHideFocus.Location = new System.Drawing.Point(0, 0);
- this.labelHideFocus.Name = "labelHideFocus";
- this.labelHideFocus.Size = new System.Drawing.Size(0, 12);
- this.labelHideFocus.TabIndex = 0;
- //
- // dkDataGridView
- //
- dataGridViewCellStyle1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(235)))), ((int)(((byte)(235)))));
- this.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1;
- this.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single;
- dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
- dataGridViewCellStyle2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(48)))), ((int)(((byte)(58)))), ((int)(((byte)(70)))));
- dataGridViewCellStyle2.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
- dataGridViewCellStyle2.ForeColor = System.Drawing.Color.White;
- dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
- dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
- dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
- this.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle2;
- this.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
- this.ColumnHeadersHeight = 25;
- this.Controls.Add(this.labelHideFocus);
- this.EnableHeadersVisualStyles = false;
- dataGridViewCellStyle3.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(159)))), ((int)(((byte)(39)))), ((int)(((byte)(39)))));
- this.RowsDefaultCellStyle = dataGridViewCellStyle3;
- this.RowTemplate.Height = 25;
- this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.dkDataGridView_MouseDown);
- this.RowEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.dkDataGridView_RowEnter);
- this.ColumnHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dkDataGridView_ColumnHeaderMouseClick);
- this.ReadOnlyChanged += new System.EventHandler(this.dkDataGridView_ReadOnlyChanged);
- this.CellValidated += new System.Windows.Forms.DataGridViewCellEventHandler(this.dkDataGridView_CellValidated);
- this.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dkDataGridView_RowPostPaint);
- this.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.dkDataGridView_PreviewKeyDown);
- this.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dkDataGridView_CellEndEdit);
- this.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.dkDataGridView_EditingControlShowing);
- this.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dkDataGridView_DataError);
- this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dkDataGridView_EscKeyDown);
- this.CellEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.dkDataGridView_CellEnter);
- this.RowHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dkDataGridView_RowHeaderMouseClick);
- ((System.ComponentModel.ISupportInitialize)(this)).EndInit();
- this.ResumeLayout(false);
- this.PerformLayout();
- }
- private void dkDataGridView_ColumnHeaderMouseClick(object sender,
- DataGridViewCellMouseEventArgs e)
- {
- string sort = "ASC";
- string sortColumns = "";
- int columnIndex = e.ColumnIndex;
- DataGridViewColumn column = this.Columns[columnIndex];
- string colName = column.Name;
- string colPropertyName = column.DataPropertyName;
- if (this.AllowUserToSortRows == false)
- {
- return;
- }
- if (columnIndex < 0 || this.Columns.Count <= columnIndex)
- {
- throw new ArgumentException("列索引超出范围。");
- }
- if (string.IsNullOrEmpty(colPropertyName))
- {
- return;
- }
- // 点击同一列进行排序时,切换升序和降序
- if (colName.Equals(_sortColumnName))
- {
- if (_sortOrderType == SortOrder.Ascending)
- {
- _sortOrderType = SortOrder.Descending;
- sort = "DESC";
- }
- else
- {
- _sortOrderType = SortOrder.Ascending;
- sort = "ASC";
- }
- }
- else
- {
- // 不是同一列进行排序时,按升序排序
- _sortOrderType = SortOrder.Ascending;
- _sortColumnName = colName;
- sort = "ASC";
- }
- if (!string.IsNullOrEmpty(SortOrderColumnName))
- {
- sortColumns = this.AnalysisSortColumn(_sortColumnName, sort);
- if (!string.IsNullOrEmpty(sortColumns))
- {
- DataTable dataTable = (DataTable)this.DataSource;
- DataView dataView = dataTable.DefaultView;
- dataView.Sort = sortColumns;
- this.DataSource = dataView.Table;
- this.Columns[_sortColumnName].HeaderCell.SortGlyphDirection = _sortOrderType;
- }
- }
- this.OnSelectionChanged(e);
- }
- private string AnalysisSortColumn(string currentColumn, string sortDirection)
- {
- string retColumn = "";
- string[] orderColumn = this.SortOrderColumnName.Split(';');
- int i = 0;
- for (i = 0; i < orderColumn.Length; i++)
- {
- string[] tmpColumn = orderColumn[i].Split(':');
- if (currentColumn.Equals(tmpColumn[0]))
- {
- retColumn = tmpColumn[1];
- break;
- }
- }
- string[] sortCols = retColumn.Split(',');
- retColumn = sortCols[0] + " " + sortDirection;
- for (i = 1; i < sortCols.Length; i++)
- {
- retColumn = retColumn + "," + sortCols[0] + " " + sortDirection;
- }
- return retColumn;
- }
- #endregion
- }
- #region 剪贴板处理
- public partial class dkDataGridView
- {
- #region 成员变量
- private ClipboardType _clipboardType = ClipboardType.InnerAndDisp;
- #endregion
- #region 属性
- [System.ComponentModel.DefaultValue(ClipboardType.InnerAndDisp)]
- public ClipboardType ClipboardType
- {
- get
- {
- return _clipboardType;
- }
- set
- {
- _clipboardType = value;
- }
- }
- #endregion
- #region 重写方法/函数
- protected override void OnSizeChanged(EventArgs e)
- {
- try
- {
- if (_isOpenTotalRow)
- {
- SetTxtTop();
- SetTxtLeft();
- }
- base.OnSizeChanged(e);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
- {
- //if (keyData == Keys.Enter)
- //{
- // SendKeys.Send("{Tab}");
- // return true;
- //}
- const int WM_KEYDOWN = 0x0100;
- const int WM_KEYUP = 0x0101;
- Keys keyCode = (Keys)(int)keyData & Keys.KeyCode;
- switch (msg.Msg)
- {
- case WM_KEYDOWN:
- break;
- case WM_KEYUP:
- if (keyCode == Keys.Delete)
- {
- if (this.ReadOnly || !this.Enabled)
- {
- return true;
- }
- if (0 == this.SelectedRows.Count)
- {
- if (this.EditingControl != null)
- {
- break;
- }
- DataGridViewCell cell = this.CurrentCell;
- if (cell != null && !cell.ReadOnly)
- {
- if (!Utility.IsNull(cell.Value))
- {
- if (this.BeginEdit(false))
- {
- if (this.EditingControl != null)
- {
- this.EditingControl.Text = null;
- }
- this.EndEdit();
- }
- }
- }
- }
- else
- {
- if (this.AllowUserToDeleteRows)
- {
- return false;
- }
- }
- }
- else if (keyCode == Keys.Escape)
- {
- return false;
- }
- break;
- }
- return base.ProcessCmdKey(ref msg, keyData);
- }
- #endregion
- #region 公开方法/函数
- public bool IsCopyData()
- {
- // DataTable信息转换成csv形式
- string csvInner = null;
- string csvDisp = null;
- if (this.ClipboardType == ClipboardType.InnerAndDisp)
- {
- csvInner = ToCsvString(false, true, false, false);
- csvDisp = ToCsvString(true, true, true, false);
- }
- else
- {
- csvInner = ToCsvString(false, true, false, false);
- csvDisp = csvInner;
- }
- if (string.IsNullOrEmpty(csvDisp) || string.IsNullOrEmpty(csvInner))
- {
- return false;
- }
- // 往剪贴板上拷贝数据
- DataObject dataObject = new DataObject();
- dataObject.SetData(DataFormats.Text, csvDisp);
- dataObject.SetData(ControlsConst.CLIPBOARD_FORMAT, csvInner);
- Clipboard.SetDataObject(dataObject, true);
- return true;
- }
- public bool IsPasteData()
- {
- if (this.ReadOnly || !this.Enabled)
- {
- // 不允许粘贴
- return true;
- }
- if (this.CurrentCell != null)
- {
- if (this.CurrentCell.IsInEditMode && !(
- this.CurrentCell is DataGridViewCheckBoxCell))
- {
- return false;
- }
- }
- if (CurrentDataTable == null)
- {
- return false;
- }
- DataColumnCollection columns = CurrentDataTable.Columns;
- IDataObject dataObject = Clipboard.GetDataObject();
- // 剪贴板的CVS数据转换成DataTable
- DataTable tableCsv = null;
- object data = dataObject.GetData(ControlsConst.CLIPBOARD_FORMAT);
- if (data == null)
- {
- if (dataObject.GetDataPresent(DataFormats.Text, true))
- {
- data = dataObject.GetData(DataFormats.Text, true);
- if (data == null)
- {
- return true;
- }
- }
- }
- string csv = data.ToString();
- tableCsv = CsvManager.ToDataTable(csv, false, '\t', '\"');
- if (tableCsv == null)
- {
- return true;
- }
- List<int> columnIndexList;
- int rowIndexMin, rowIndexMax;
- GetSelectedRange(out columnIndexList, out rowIndexMin, out rowIndexMax);
- // 设置DataColumn信息
- DataTable table = new DataTable();
- foreach (int columnIndex in columnIndexList)
- {
- DataGridViewColumn column = this.Columns[columnIndex];
- if (column == null)
- {
- return true;
- }
- if (column.CellType.Name == "DataGridViewSearchFileBoxCellEx")
- {
- continue;
- }
- table.Columns.Add(column.DataPropertyName);
- }
- DataRowView rowView;
- DataRow drowRow;
- int rowCount = tableCsv.Rows.Count;
- int viewRowCount = Rows.Count;
- int columnCount = tableCsv.Columns.Count;
- int j = 0;
- for (int i = rowIndexMin; i <= rowIndexMax; i++)
- {
- try
- {
- if (columnIndexList.Count < Columns.Count)
- {
- if (!Rows[i].IsNewRow)
- {
- rowView = GetDataRowView(i);
- if (rowView == null)
- {
- continue;
- }
- for (int k = 0; k < columnIndexList.Count; k++)
- {
- int columnIndex = columnIndexList[k];
- if (!this.Rows[i].Cells[columnIndex].ReadOnly)
- {
- rowView[this.Columns[columnIndex].DataPropertyName] =
- ConvertValue(tableCsv.Rows[j][k].ToString());
- }
- }
- j++;
- }
- else
- {
- for (; j < rowCount; j++)
- {
- drowRow = CurrentDataTable.NewRow();
- for (int k = 0; k < columnIndexList.Count; k++)
- {
- int columnIndex = columnIndexList[k];
- if (!this.Rows[i].Cells[columnIndex].ReadOnly)
- {
- drowRow[this.Columns[columnIndex].DataPropertyName] =
- ConvertValue(tableCsv.Rows[j][k].ToString());
- }
- }
- CurrentDataTable.Rows.Add(drowRow);
- }
- this.Rows.RemoveAt(this.CurrentCell.RowIndex);
- }
- }
- else
- {
- if (!Rows[i].IsNewRow)
- {
- rowView = GetDataRowView(i);
- if (rowView == null)
- {
- continue;
- }
- for (int k = 0; k < columnCount; k++)
- {
- try
- {
- if (!this.Rows[i].Cells[k].ReadOnly)
- {
- rowView[table.Columns[k].ColumnName] =
- ConvertValue(tableCsv.Rows[j][k].ToString());
- }
- }
- catch (ReadOnlyException)
- {
- }
- }
- rowView.EndEdit();
- j++;
- if (rowCount <= j)
- {
- break;
- }
- }
- else
- {
- for (; j < rowCount; j++)
- {
- drowRow = CurrentDataTable.NewRow();
- for (int k = 0; k < columnCount; k++)
- {
- try
- {
- if (!this.Rows[i].Cells[k].ReadOnly)
- {
- drowRow[table.Columns[k].ColumnName] =
- ConvertValue(tableCsv.Rows[j][k].ToString());
- }
- }
- catch (ReadOnlyException)
- {
- }
- }
- CurrentDataTable.Rows.Add(drowRow);
- }
- }
- }
- }
- catch (IndexOutOfRangeException)
- {
- break;
- }
- catch (Exception ex)
- {
- Debug.Assert(false, "错误", ex.Message);
- MessageBox.Show(ex.Message);
- return true;
- }
- }
- if (CurrentDataTable != null && CurrentDataTable.Rows.Count + 2 == this.Rows.Count)
- {
- this.Rows.RemoveAt(this.Rows.Count - 2);
- }
- if (this.CurrentCell != null)
- {
- this.Refresh();
- }
- return true;
- }
- /// <summary>
- /// 打开合计行
- /// </summary>
- public void OpenTotalRow()
- {
- try
- {
- _isOpenTotalRow = true;
- NewText(string.Empty, 0);//设置RowHeader对应的TextBox;
- SetTxtLeft();
- SetTxtTop();
- this.HorizontalScrollBar.VisibleChanged += new EventHandler(HorizontalScrollBar_VisibleChanged);//水平
- this.VerticalScrollBar.VisibleChanged += new EventHandler(VerticalScrollBar_VisibleChanged); //竖直
- this.HorizontalScrollBar.ValueChanged += new EventHandler(HorizontalScrollBar_ValueChanged);
- _columnInfos = this.GetDataGridViewColumnInfos();
- if (_columnInfos != null)
- {
- for (int i = 0; i < _columnInfos.Length; i++)
- {
- if (_columnInfos[i].Visible)
- {
- NewText(_columnInfos[i].DataPropertyName, i);
- }
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- void HorizontalScrollBar_ValueChanged(object sender, EventArgs e)
- {
- try
- {
- SetTxtLeft();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- void VerticalScrollBar_VisibleChanged(object sender, EventArgs e)
- {
- try
- {
- if (VerticalScrollBar.Visible)
- {
- int width = 0;
- if (findTextBox("txt" + this.Name) != null)
- {
- width = findTextBox("txt" + this.Name).Width;
- }
- this.VerticalScrollBar.Maximum = this.VerticalScrollBar.Maximum + width;
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- void HorizontalScrollBar_VisibleChanged(object sender, EventArgs e)
- {
- try
- {
- SetTxtTop();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- //求和
- protected override void OnCellEndEdit(DataGridViewCellEventArgs e)
- {
- if (_isOpenTotalRow && IsAutoCountSum)
- {
- if (this.dt == null) return;
- string s = this.CurrentCell.Value + "";
- bool isValue = false;
- foreach (DataColumn dc in dt.Columns)
- {
- if (dc.ColumnName == this.Columns[e.ColumnIndex].DataPropertyName)
- {
- if (TotalSumColumns != null && TotalSumColumns.Count > 0)
- {
- if (TotalSumColumns.Contains(dc.ColumnName))
- {
- isValue = dc.DataType.IsValueType;
- break;
- }
- }
- else
- {
- isValue = dc.DataType.IsValueType;
- break;
- }
- }
- }
- decimal sumValue = 0;
- if (isValue)
- {
- try
- {
- if (this.Columns[e.ColumnIndex].Visible)
- {
- object o = dt.Compute("SUM(" + this.Columns[e.ColumnIndex].DataPropertyName + ")", filter);
- decimal.TryParse(o.ToString(), out sumValue);
- string format = "F0";
- if (!string.IsNullOrEmpty(this.Columns[e.ColumnIndex].DefaultCellStyle.Format))
- {
- format = this.Columns[e.ColumnIndex].DefaultCellStyle.Format;
- }
- if (IsSubTotalFlag)
- {
- if (!this.Columns[e.ColumnIndex].Name.Contains("Box") &&
- !this.Columns[e.ColumnIndex].Name.Contains("Piece"))
- {
- findTextBox("txt" + this.Columns[e.ColumnIndex].Name.ToString()).Text
- = (sumValue / 2).ToString(format);
- }
- else
- {
- findTextBox("txt" + this.Columns[e.ColumnIndex].Name.ToString()).Text
- = sumValue.ToString(format);
- }
- }
- else
- {
- findTextBox("txt" + this.Columns[e.ColumnIndex].Name.ToString()).Text
- = sumValue.ToString(format);
- }
- }
- }
- catch (DataException)
- { }
- }
- }
- base.OnCellEndEdit(e);
- }
- protected override void OnDataSourceChanged(EventArgs e)
- {
- try
- {
- base.OnDataSourceChanged(e);
- if (_isOpenTotalRow)
- {
- if (dt == null || _columnInfos == null) return;
- // 解决合计行遮住最后一行的bug
- if (dt.Rows.Count > 0)
- {
- int height = dt.Rows.Count * this.CellHeight + this.ColumnHeadersHeight;
- if (findTextBox("txt" + this.Name) != null)
- {
- height += findTextBox("txt" + this.Name).Height;
- }
- if (height > this.Height)
- {
- if (!this.AllowUserToAddRows)
- {
- this.AllowUserToAddRows = true;
- this.ReadOnly = true;
- }
- }
- else
- {
- if (this.AllowUserToAddRows)
- {
- this.AllowUserToAddRows = false;
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- /// <summary>
- /// 重新计算合计行
- /// </summary>
- public void CountTotalRow()
- {
- try
- {
- if (_isOpenTotalRow)
- {
- if (dt == null || _columnInfos == null) return;
- //for (int j = 0; j < dt.Rows.Count; j++)
- //{
- // for (int i = 0; i < dt.Columns.Count; i++)
- // {
- // if (("Decimal".Equals(dt.Columns[i].DataType.Name)
- // || "Int".Equals(dt.Columns[i].DataType.Name)
- // || "Double".Equals(dt.Columns[i].DataType.Name)))
- // {
- // DataGridViewCell cell = this.Rows[this.Rows.Count - 1].Cells[dt.Columns[i].ColumnName];
- // dt.Rows[j][i] = cell.FormattedValue;
- // }
- // }
- //}
- // 解决合计行遮住最后一行的bug
- //if (dt.Rows.Count > 0)
- //{
- // int height = dt.Rows.Count * this.CellHeight + this.ColumnHeadersHeight + findTextBox("txt").Height;
- // if (height > this.Height)
- // {
- // if (!this.AllowUserToAddRows)
- // {
- // this.AllowUserToAddRows = true;
- // this.ReadOnly = true;
- // }
- // }
- // else
- // {
- // if (this.AllowUserToAddRows)
- // {
- // this.AllowUserToAddRows = false;
- // }
- // }
- //}
- string totalCountNameFormat = string.Empty;
- for (int i = 0; i < _columnInfos.Length; i++)
- {
- if (!string.IsNullOrEmpty(TotalCountName) && TotalCountName.Equals(_columnInfos[i].DataPropertyName))
- {
- totalCountNameFormat = _columnInfos[i].DefaultCellStyle.Format;
- }
- bool isValue = false;
- foreach (DataColumn dc in dt.Columns)
- {
- if (dc.ColumnName == _columnInfos[i].DataPropertyName)
- {
- if (TotalSumColumns != null && TotalSumColumns.Count > 0)
- {
- if (TotalSumColumns.Contains(dc.ColumnName))
- {
- isValue = dc.DataType.IsValueType;
- break;
- }
- }
- else
- {
- isValue = dc.DataType.IsValueType;
- break;
- }
- }
- }
- decimal sumValue = 0;
- if (isValue)
- {
- try
- {
- if (_columnInfos[i].Visible)
- {
- object o = dt.Compute("SUM([" + _columnInfos[i].DataPropertyName + "])", filter);
- decimal.TryParse(o.ToString(), out sumValue);
- TextBox tb = findTextBox("txt" + _columnInfos[i].DataPropertyName);
- if (tb != null)
- {
- if (dt.Rows.Count == 0 && sumValue == 0)
- {
- tb.Text = string.Empty;
- }
- else
- {
- // 周兴 2016-10-10 修改 合计行去掉小数位数后多余的0
- //if (!string.IsNullOrEmpty(_columnInfos[i].DefaultCellStyle.Format))
- //{
- // if (IsSubTotalFlag)
- // {
- // if (!_columnInfos[i].DataPropertyName.Contains("Box") &&
- // !_columnInfos[i].DataPropertyName.Contains("Piece"))
- // {
- // tb.Text = (sumValue / 2).ToString(_columnInfos[i].DefaultCellStyle.Format);
- // }
- // else
- // {
- // tb.Text = sumValue.ToString(_columnInfos[i].DefaultCellStyle.Format);
- // }
-
- // }
- // else
- // {
- // tb.Text = sumValue.ToString(_columnInfos[i].DefaultCellStyle.Format);
- // }
- //}
- //else
- //{
- // if (IsSubTotalFlag)
- // {
- // if (!_columnInfos[i].DataPropertyName.Contains("Box") &&
- // !_columnInfos[i].DataPropertyName.Contains("Piece"))
- // {
- // tb.Text = (sumValue / 2) + "";
- // }
- // else
- // {
- // tb.Text = sumValue + "";
- // }
- // }
- // else
- // {
- // tb.Text = sumValue + "";
- // }
- //}
- if (IsSubTotalFlag)
- {
- if (!_columnInfos[i].DataPropertyName.Contains("Box") &&
- !_columnInfos[i].DataPropertyName.Contains("Piece"))
- {
- tb.Text = (sumValue / 2).ToString("####.######");
- }
- else
- {
- tb.Text = sumValue.ToString("####.######");
- }
- }
- else
- {
- tb.Text = sumValue.ToString("####.######");
- }
- }
- }
- }
- }
- catch (DataException)
- { }
- }
- }
- // 用合计的值进行重新计算
- if (!string.IsNullOrEmpty(TotalCountName))
- {
- if (!string.IsNullOrEmpty(TotalCountFormula))
- {
- if (TotalCountFormula.IndexOf("|") >= 0)
- {
- string[] formulas = TotalCountFormula.Split('|');
- string formula = formulas[0];
- string formula1 = formulas[1]; // A1:ss,A2:tt
- string[] formula2s = formula1.Split(',');
- TextBox tb = null;
- TextBox tboo = findTextBox("txt" + TotalCountName);
- if (tboo != null)
- {
- for (int i = 0; i < formula2s.Length; i++)
- {
- string[] ss = formula2s[i].Split(':');
- tb = findTextBox("txt" + ss[1]);
- if (tb != null && !string.IsNullOrEmpty(tb.Text))
- {
- formula = formula.Replace(ss[0], tb.Text);
- }
- else
- {
- tboo.Text = string.Empty;
- break;
- }
- }
- try
- {
- // 计算值
- MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControlClass();
- sc.Language = "JavaScript";
- string result = sc.Eval(formula) + "";
- if (!string.IsNullOrEmpty(result))
- {
- tboo.Text = Convert.ToDecimal(result).ToString("F2");
- }
- }
- catch (Exception)
- {
- tboo.Text = string.Empty;
- }
- }
- }
- TextBox tbo = findTextBox("txt" + TotalCountName);
- try
- {
- string fomulastring = TotalCountFormula;
- string[] formula = fomulastring.Split(new char[] { '+', '-', '*', '/', '(', ')' });
- TextBox tb = null;
- for (int i = 0; i < formula.Length; i++)
- {
- tb = findTextBox("txt" + formula[i]);
- if (tb != null && !string.IsNullOrEmpty(tb.Text))
- {
- fomulastring = fomulastring.Replace(formula[i], tb.Text);
- }
- else
- {
- tbo.Text = string.Empty;
- break;
- }
- }
- // 计算值
- MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControlClass();
- sc.Language = "JavaScript";
- string result = sc.Eval(fomulastring) + "";
- if (!string.IsNullOrEmpty(result))
- {
- if (string.IsNullOrEmpty(totalCountNameFormat))
- {
- totalCountNameFormat = "####.######";
- }
- tbo.Text = Convert.ToDecimal(result).ToString(totalCountNameFormat);
- }
- }
- catch (Exception)
- {
- tbo.Text = string.Empty;
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- /// <summary>
- /// 清除合计行
- /// </summary>
- public void ClearTotalRow()
- {
- try
- {
- //if (_columnInfos != null)
- //{
- // //for (int i = 0; i < _columnInfos.Length; i++)
- // //{
- // // this.Controls.RemoveByKey("txt" + _columnInfos[i].DataPropertyName);
- // //}
- //}
- for (int i = this.Controls.Count - 1; i >= 0; i--)
- {
- if (this.Controls[i].Name.StartsWith("txt") && !"txt".Equals(this.Controls[i].Name))
- {
- this.Controls.RemoveAt(i);
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- /// <summary>
- /// 清除合计行
- /// </summary>
- public void ClearTotalRowData()
- {
- try
- {
- for (int i = this.Controls.Count - 1; i >= 0; i--)
- {
- if (this.Controls[i].Name.StartsWith("txt") && !"txt".Equals(this.Controls[i].Name))
- {
- TextBox tb = this.Controls[i] as TextBox;
- if (tb != null)
- {
- tb.Clear();
- }
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- /// <summary>
- /// 重新生成合计行并计算合计行
- /// </summary>
- public void CountNewTextAndTotalRow()
- {
- try
- {
- if (_columnInfos != null)
- {
- for (int i = 0; i < _columnInfos.Length; i++)
- {
- this.Controls.RemoveByKey("txt" + _columnInfos[i].DataPropertyName);
- }
- }
- _isOpenTotalRow = true;
- _columnInfos = GetDataGridViewColumnInfos();
- if (_columnInfos != null)
- {
- this.HorizontalScrollingOffset = 0;
- NewText(string.Empty, 0);
- for (int i = 0; i < _columnInfos.Length; i++)
- {
- if (_columnInfos[i].Visible)
- {
- NewText(_columnInfos[i].DataPropertyName, i);
- }
- }
- CountTotalRow();
- }
- IsAutoResizeColumns = false;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- //设置TextBox的Top,使之保持在DagtaGridView最下方;
- private void SetTxtTop()
- {
- try
- {
- if (_columnInfos == null) return;
- int topTxt = 0;
- if (HorizontalScrollBar.Visible)
- topTxt = this.Height - this.HorizontalScrollBar.Height;
- else
- topTxt = this.Height;
- TextBox t = findTextBox("txt" + this.Name);
- if (t != null)
- {
- t.Top = topTxt - t.Height;
- for (int i = 0; i < _columnInfos.Length; i++)
- {
- if (this._columnInfos[i].Visible)
- {
- TextBox t1 = findTextBox("txt" + this._columnInfos[i].DataPropertyName);
- if (t1 != null)
- {
- t1.Top = t.Top;
- t1.TextAlign = HorizontalAlignment.Right;
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- //根据TextBox的名字找到TextBox;
- private TextBox findTextBox(string txtName)
- {
- try
- {
- foreach (Control ctl in this.Controls)
- {
- if (ctl.Name == txtName)
- return ctl as TextBox;
- }
- return null;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- //设置TextBox的Left,使之与对应的Column的Left对应
- private void SetTxtLeft()
- {
- try
- {
- if (_columnInfos == null) return;
- int left = 0;
- bool flag = false;
- if (!_isFrozen)
- {
- flag = true;
- }
- for (int i = 0; i < _columnInfos.Length; i++)
- {
- if (_isFrozen)
- {
- if (!_columnInfos[i].Frozen)
- {
- flag = true;
- }
- }
- if (flag)
- {
- TextBox tt = findTextBox("txt" + this._columnInfos[i].DataPropertyName);
- if (tt != null)
- {
- left = getLeft(_columnInfos[i].DataPropertyName, i);
- if (left < RowHeadersWidth - HorizontalScrollingOffset)
- {
- tt.Visible = false;
- }
- else
- {
- tt.TextAlign = HorizontalAlignment.Right;
- tt.Visible = true;
- tt.Left = left;
- }
- }
- }
- }
- //for (int i = 0; i < this.FirstDisplayedScrollingColumnIndex; i++)
- //{
- // TextBox tt = findTextBox("txt" + this._columnInfos[i].DataPropertyName);
- // if (tt != null)
- // {
- // tt.Visible = false;
- // }
- //}
- //int firstIndex = FirstDisplayedScrollingColumnIndex > 0 ? FirstDisplayedScrollingColumnIndex : 0;
- //for (int j = firstIndex; j < _columnInfos.Length; j++)
- //{
- // if (_columnInfos != null && _columnInfos[j].Visible)
- // {
- // TextBox t = findTextBox("txt" + _columnInfos[j].DataPropertyName);
- // if (t != null)
- // {
- // t.TextAlign = HorizontalAlignment.Right;
- // t.Visible = true;
- // t.Left = getLeft(_columnInfos[j].DataPropertyName, j);
- // }
- // }
- //}
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- //得到Column的Left
- public int getLeft(string columnName, int endIndex)
- {
- try
- {
- if (string.IsNullOrEmpty(columnName) || _columnInfos == null) return 0;
- int left = this.RowHeadersWidth;
- //int left = this.RowHeadersWidth - this.FirstDisplayedScrollingColumnHiddenWidth;
- //int firstIndex = FirstDisplayedScrollingColumnIndex > 0 ? FirstDisplayedScrollingColumnIndex : 0;
- //for (int i = firstIndex; i < infos[columnName].Index; i++)
- //{
- // left += Columns[i].Width;
- //}
- for (int i = 0; i < endIndex; i++)
- {
- left += _columnInfos[i].Width;
- }
- left -= this.HorizontalScrollingOffset;
- return left;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- //生成TextBox;
- private void NewText(string columnName, int columnIndex)
- {
- try
- {
- TextBox t = new TextBox();
- t.ReadOnly = true;
- if (string.IsNullOrEmpty(columnName))
- {
- TextBox t1 = findTextBox("txt" + this.Name);
- if (t1 == null)
- {
- t.Name = "txt" + this.Name;
- t.Width = this.RowHeadersWidth;
- t.Text = "合计";
- }
- else
- {
- return;
- }
- }
- else
- {
- t.TextAlign = HorizontalAlignment.Right;
- t.Name = "txt" + columnName;
- t.Width = _columnInfos[columnIndex].Width;
- }
- t.BackColor = System.Drawing.Color.LightBlue;
- int topTxt = 0;
- if (HorizontalScrollBar.Visible)
- topTxt = this.Height - this.HorizontalScrollBar.Height;
- else
- topTxt = this.Height;
- t.Top = topTxt - t.Height;
- t.Left = getLeft(columnName, columnIndex);
- if (findTextBox(t.Name) == null)
- {
- this.Controls.Add(t);
- t.Show();
- }
- else
- {
- if (!("txt" + this.Name).Equals(t.Name))
- {
- this.Controls.RemoveByKey(t.Name);
- this.Controls.Add(t);
- t.Show();
- }
- else
- {
- this.Controls.Add(t);
- t.Show();
- }
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- #endregion
- #region 受保护的方法/函数
- protected void GetSelectedRange(out List<int> columnIndexList,
- out int rowIndexMin, out int rowIndexMax)
- {
- List<int> list = new List<int>();
- columnIndexList = new List<int>();
- rowIndexMin = -1;
- rowIndexMax = -1;
- foreach (DataGridViewCell cell in this.SelectedCells)
- {
- if (rowIndexMin < 0)
- {
- // 第一次的情况
- rowIndexMin = cell.RowIndex;
- rowIndexMax = cell.RowIndex;
- }
- else
- {
- // 第一次以后的情况
- if (cell.RowIndex < rowIndexMin)
- {
- rowIndexMin = cell.RowIndex;
- }
- if (rowIndexMax < cell.RowIndex)
- {
- rowIndexMax = cell.RowIndex;
- }
- }
- if (!list.Contains(cell.ColumnIndex))
- {
- list.Add(cell.ColumnIndex);
- }
- }
- while (true)
- {
- int minValue = int.MaxValue;
- int minValueIndex = -1;
- for (int i = 0; i < list.Count; i++)
- {
- if (this.Columns[list[i]].DisplayIndex < minValue)
- {
- minValue = this.Columns[list[i]].DisplayIndex;
- minValueIndex = i;
- }
- }
- if (minValueIndex < 0)
- {
- return;
- }
- int dataGridViewInnerColumnIndex = list[minValueIndex];
- columnIndexList.Add(dataGridViewInnerColumnIndex);
- list.RemoveAt(minValueIndex);
- }
- }
- protected object ConvertValue(string value)
- {
- if (string.IsNullOrEmpty(value))
- {
- return DBNull.Value;
- }
- else
- {
- return value.Replace("\r\n", "\n").Replace("\n", "\r\n");
- }
- }
- #endregion
- }
- #endregion
- #region DataGridView信息的保存和复原
- public partial class dkDataGridView
- {
- #region 成员变量
- private bool _isSaveDataGridViewData = false; // 需要保存数据标识
- private bool _isSaveDataGridSetting = true; // DataGridView设定数据
- private DataGridViewSettings _settings = null;
- #endregion
- #region 属性
- /// <summary>
- /// 设定或者获取DataGridView设定数据(列的顺序·宽度)保存的标识
- /// </summary>
- [System.ComponentModel.Browsable(true)]
- [System.ComponentModel.DefaultValue(true)]
- [System.ComponentModel.Description("设定或者获取DataGridView设定数据(列的顺序·宽度)保存的标识")]
- public bool IsSaveDataGridViewSetting
- {
- get
- {
- return _isSaveDataGridSetting;
- }
- set
- {
- _isSaveDataGridSetting = value;
- }
- }
- [System.ComponentModel.Browsable(true)]
- [System.ComponentModel.DefaultValue(false)]
- [System.ComponentModel.Description("设定或者获取DataGridView数据保存的标识")]
- public bool IsSaveDataGridViewData
- {
- get
- {
- return _isSaveDataGridViewData;
- }
- set
- {
- _isSaveDataGridViewData = value;
- }
- }
- private DataGridViewSettings DataGridViewSettings
- {
- get
- {
- if (_settings == null)
- {
- _settings = new DataGridViewSettings();
- System.Text.StringBuilder sbKey = new System.Text.StringBuilder();
- Control control = this;
- while (control != null)
- {
- sbKey.Append("_");
- sbKey.Append(control.Name);
- control = control.Parent;
- }
- _settings.SettingsKey = sbKey.ToString();
- }
- return _settings;
- }
- }
- #endregion
- #region 方法或者函数
- public void SaveDataGridViewData()
- {
- if (!IsSaveDataGridViewData)
- {
- return;
- }
- this.DataGridViewSettings.DataGridViewColumnInfos = GetDataGridViewColumnInfos();
- this.DataGridViewSettings.Save();
- }
- public void RestoreDataGridViewData()
- {
- if (!IsSaveDataGridViewData)
- {
- return;
- }
- DataGridViewColumnInfo[] infos = this.DataGridViewSettings.DataGridViewColumnInfos;
- if (infos == null || infos.Length == 0)
- {
- return;
- }
- for (int i = 0; i < infos.Length; i++)
- {
- DataGridViewColumnInfo info = infos[i];
- string strColumnName = info.ColumnName;
- if (this.Columns.Contains(strColumnName))
- {
- if (this.Columns[strColumnName].DisplayIndex != i)
- {
- this.Columns[strColumnName].DisplayIndex = i;
- }
- this.Columns[strColumnName].Width = info.Width;
- }
- }
- }
- private DataGridViewColumnInfo[] GetDataGridViewColumnInfos()
- {
- List<DataGridViewColumnInfo> list = new List<DataGridViewColumnInfo>();
- for (int i = 0; i < this.Columns.Count; i++)
- {
- foreach (DataGridViewColumn column in this.Columns)
- {
- if (column.DisplayIndex == i && column.Visible)
- {
- DataGridViewColumnInfo info = new DataGridViewColumnInfo();
- info.ColumnName = column.Name;
- info.ColumnText = column.HeaderText;
- info.TreeColumnText = GetTreeColumnText(column);
- info.Width = column.Width;
- info.Visible = column.Visible;
- info.DataPropertyName = column.DataPropertyName;
- info.DefaultCellStyle = column.DefaultCellStyle;
- info.Frozen = column.Frozen;
- list.Add(info);
- break;
- }
- }
- }
- return list.ToArray();
- }
- private string GetTreeColumnText(DataGridViewColumn column)
- {
- if (this.ColumnTreeViewNode != null)
- {
- object[] colList = ColumnList.ToArray();
- TreeNode tn = (TreeNode)colList[column.Index];
- System.Text.StringBuilder sb = new System.Text.StringBuilder();
- while (tn != null)
- {
- if (sb.Length > 0)
- {
- sb.Insert(0, tn.Name + "→");
- }
- else
- {
- sb.Append(column.HeaderText);
- }
- tn = tn.Parent;
- }
- return sb.ToString();
- }
- return column.HeaderText;
- }
- #endregion
- }
- #region DataGridView的列信息
- [Serializable]
- internal sealed class DataGridViewColumnInfo
- {
- public string ColumnName
- {
- get;
- set;
- }
- public string DataPropertyName
- {
- get;
- set;
- }
- public string ColumnText
- {
- get;
- set;
- }
- public string TreeColumnText
- {
- get;
- set;
- }
- public int Width
- {
- get;
- set;
- }
- public bool Visible
- {
- get;
- set;
- }
- public DataGridViewCellStyle DefaultCellStyle
- {
- get;
- set;
- }
- public bool Frozen
- {
- get;
- set;
- }
- }
- #endregion
- #region DataGridView信息保存类
- [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
- [global::System.CodeDom.Compiler.GeneratedCodeAttribute(
- "Dongke.IBOSS.Framework.Controls.dkDataGridView", "0.0.0.0")]
- internal sealed class DataGridViewSettings :
- global::System.Configuration.ApplicationSettingsBase
- {
- private static DataGridViewSettings _defaultInstance = ((DataGridViewSettings)(
- global::System.Configuration.ApplicationSettingsBase.Synchronized(
- new DataGridViewSettings())));
- public static DataGridViewSettings Default
- {
- get
- {
- return _defaultInstance;
- }
- }
- [global::System.Configuration.UserScopedSettingAttribute()]
- [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
- [global::System.Configuration.DefaultSettingValueAttribute(null)]
- [global::System.Configuration.SettingsSerializeAs(
- System.Configuration.SettingsSerializeAs.Binary)]
- public DataGridViewColumnInfo[] DataGridViewColumnInfos
- {
- get
- {
- return (DataGridViewColumnInfo[])this["DataGridViewColumnInfos"];
- }
- set
- {
- this["DataGridViewColumnInfos"] = value;
- }
- }
- }
- #endregion
- #endregion
- #region 过滤处理
- public partial class dkDataGridView
- {
- #region 公开方法/函数
- public void FilterRow(FilterType filterType)
- {
- try
- {
- if (this.CurrentCell == null)
- {
- return;
- }
- FilterRow(this.CurrentCell.ColumnIndex, filterType, this.CurrentCell.Value);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- public void FilterRow(int columnIndex, FilterType filterType, object value)
- {
- try
- {
- // DataTable不存在的情况,返回
- if (this.CurrentDataTable == null || this.CurrentDataTable.Rows.Count < 1)
- {
- return;
- }
- DataGridViewColumn column = this.Columns[columnIndex];
- if (column == null)
- {
- return;
- }
- if (string.IsNullOrEmpty(column.DataPropertyName))
- {
- return;
- }
- if (!(this.DataSource is DataView))
- {
- this.CurrentDataTable.DefaultView.AllowDelete = this.AllowUserToDeleteRows;
- this.CurrentDataTable.DefaultView.AllowEdit = this.AllowUserToModifyRows;
- this.CurrentDataTable.DefaultView.AllowNew = this.AllowUserToAddRows;
- //this.DataSource = this.CurrentDataTable.DefaultView.ToTable();
- this.DataMember = string.Empty;
- }
- string strValueString = value as string;
- if (!string.IsNullOrEmpty(strValueString))
- {
- if (2 < strValueString.Length)
- {
- if (!System.Text.RegularExpressions.Regex.IsMatch(strValueString, "^.[^\\%]*.$"))
- {
- MessageBox.Show(ControlsTips.DK_DataGridView_LikeError);
- return;
- }
- }
- }
- bool isNumber = false;
- string filter = string.Empty;
- if (!string.IsNullOrEmpty(strValueString))
- {
- if (("Decimal".Equals(column.ValueType.Name)
- || "Int".Equals(column.ValueType.Name)
- || "Double".Equals(column.ValueType.Name)))
- {
- if (strValueString.StartsWith(">")
- || strValueString.StartsWith("<")
- || strValueString.StartsWith("="))
- {
- string tempValue = strValueString.Substring(1);
- decimal tmpValueDec = 0;
- bool flag = decimal.TryParse(tempValue, out tmpValueDec);
- if (flag)
- {
- isNumber = true;
- filter = column.DataPropertyName + strValueString;
- }
- }
- else
- {
- if (strValueString.IndexOf("-") > 0)
- {
- string[] values = strValueString.Split('-');
- decimal minValue = 0;
- decimal maxValue = 0;
- bool flag1 = decimal.TryParse(values[0], out minValue);
- bool flag2 = decimal.TryParse(values[1], out maxValue);
- if (flag1 && flag2)
- {
- isNumber = true;
- filter = column.DataPropertyName + " > " + minValue + " AND " + column.DataPropertyName + " < " + maxValue;
- }
- }
- }
- }
- }
- if (!isNumber)
- {
- bool isHavedata = false;
- if (!string.IsNullOrEmpty(strValueString)
- && (strValueString.IndexOf(",") >= 0 || strValueString.IndexOf(",") >= 0))
- {
- string[] values = strValueString.Split(new char[] { ',', ',' });
- if (("Decimal".Equals(column.ValueType.Name)
- || "Int".Equals(column.ValueType.Name)
- || "Double".Equals(column.ValueType.Name)))
- {
- decimal tmpValue = 0;
- for (int i = 0; i < values.Length; i++)
- {
- bool flag = decimal.TryParse(values[i], out tmpValue);
- if (flag)
- {
- isHavedata = true;
- filter += column.DataPropertyName + " = " + tmpValue + " OR ";
- }
- }
- if (isHavedata)
- {
- filter = filter.Substring(0, filter.Length - 4);
- }
- }
- else
- {
- isHavedata = true;
- for (int i = 0; i < values.Length; i++)
- {
- filter += column.DataPropertyName + " = '" + values[i] + "' OR ";
- }
- filter = filter.Substring(0, filter.Length - 4);
- }
- }
- if (!isHavedata)
- {
- string format;
- if (Utility.IsNull(value))
- {
- format = "CONVERT([{0}], 'System.String') {1}";
- }
- else
- {
- format = "ISNULL(CONVERT([{0}], 'System.String'), '') {1}";
- }
- filter = string.Format(format, column.DataPropertyName.Replace("]", "]]"),
- GetOperatorValue(filterType, value, null));
- if (!string.IsNullOrEmpty(this.CurrentDataTable.DefaultView.RowFilter))
- {
- filter += string.Format(" AND {0}",
- this.CurrentDataTable.DefaultView.RowFilter);
- }
- }
- }
- if (this.CurrentCell != null)
- {
- this.CurrentCell = this.Rows[0].Cells[columnIndex];
- }
- this.CurrentDataTable.DefaultView.RowFilter = filter;
- if (_isOpenTotalRow)
- {
- // 重新计算合计行
- dt = this.CurrentDataTable.DefaultView.ToTable();
- CountTotalRow();
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- public void ResetFilter()
- {
- try
- {
- if (this.CurrentDataTable == null)
- {
- return;
- }
- if (this.CurrentCell != null)
- {
- this.CurrentCell = this.Rows[0].Cells[this.CurrentCell.ColumnIndex];
- }
- if (_isChildDGV && !string.IsNullOrEmpty(_viewRowFilterString))
- {
- this.CurrentDataTable.DefaultView.RowFilter = _viewRowFilterString;
- }
- else
- {
- this.CurrentDataTable.DefaultView.RowFilter = string.Empty;
- }
- if (_isOpenTotalRow)
- {
- // 重新计算合计行
- dt = this.CurrentDataTable.DefaultView.ToTable();
- CountTotalRow();
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- #endregion
- #region 受保护的方法/函数
- protected string GetOperatorValue(FilterType filterType, object value, Type columnType)
- {
- if (Utility.IsNull(value))
- {
- switch (filterType)
- {
- case FilterType.NotEqual:
- case FilterType.NotLike:
- return "IS NOT NULL";
- case FilterType.Equal:
- case FilterType.Like:
- default:
- return "IS NULL";
- }
- }
- else
- {
- string ope = "=";
- switch (filterType)
- {
- case FilterType.NotEqual:
- ope = "<>";
- break;
- case FilterType.Like:
- ope = "LIKE";
- value = ConvertRegularExpressionFilter(value + "");
- break;
- case FilterType.NotLike:
- ope = "NOT LIKE";
- value = ConvertRegularExpressionFilter(value + "");
- break;
- case FilterType.Equal:
- default:
- ope = "=";
- break;
- }
- return string.Format("{0} '{1}'", ope, value);
- }
- }
- #endregion
- }
- #endregion
- #region 右键菜单处理
- #region 右键菜单(过滤功能)
- public class ToolStripRefine : ToolStripControlHost
- {
- #region 构造函数
- public ToolStripRefine()
- : base(new RefineControl())
- {
- }
- #endregion
- #region 公开方法/函数
- public new string Text
- {
- get
- {
- return RefineControlInstance.TextBox.Text;
- }
- }
- #endregion
- #region 受保护方法/函数
- RefineControl RefineControlInstance
- {
- get
- {
- return (RefineControl)Control;
- }
- }
- #endregion
- #region 委托
- public event EventHandler RefineTextFixed;
- #endregion
- #region 重写方法
- protected override void OnSubscribeControlEvents(Control c)
- {
- base.OnSubscribeControlEvents(c);
- RefineControlInstance.TextBox.KeyDown += new KeyEventHandler(RefineControl_KeyDown);
- }
- protected override void OnUnsubscribeControlEvents(Control c)
- {
- base.OnUnsubscribeControlEvents(c);
- RefineControlInstance.TextBox.KeyDown -= new KeyEventHandler(RefineControl_KeyDown);
- }
- #endregion
- #region 事件
- private void RefineControl_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.KeyCode == Keys.Enter)
- {
- if (RefineTextFixed != null)
- {
- RefineTextFixed(this, e);
- }
- }
- }
- #endregion
- }
- #endregion
- #region 过滤控件
- class RefineControl : Control
- {
- #region 成员变量
- private Label lblRefine = new Label();
- private TextBox txtRefine = new TextBox();
- #endregion
- #region 属性
- public TextBox TextBox
- {
- get
- {
- return txtRefine;
- }
- }
- #endregion
- #region 构造函数
- public RefineControl()
- {
- // lblRefine
- lblRefine.AutoSize = true;
- lblRefine.Location = new System.Drawing.Point(0, 5);
- lblRefine.Name = "label1";
- lblRefine.Size = new System.Drawing.Size(40, 12);
- lblRefine.TabIndex = 1;
- lblRefine.Text = ControlsTips.DK_DataGridView_Refine;
- // txtRefine
- txtRefine.Location = new System.Drawing.Point(62, 2);
- txtRefine.Name = "textBox1";
- txtRefine.Size = new System.Drawing.Size(100, 19);
- txtRefine.TabIndex = 2;
- txtRefine.PreviewKeyDown += new PreviewKeyDownEventHandler(txtRefine_PreviewKeyDown);
- // RefineControl
- this.Height = 23;
- this.Width = 144;
- this.Controls.Add(lblRefine);
- this.Controls.Add(txtRefine);
- }
- #endregion
- #region 事件
- private void txtRefine_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
- {
- if (e.Alt)
- {
- e.IsInputKey = true;
- }
- }
- #endregion
- }
- #endregion
- #endregion
- #region CSV转换事件的参数类
- public class CsvConvertingEventArgs : EventArgs
- {
- #region 成员变量
- private int _columnIndex;
- private object _value;
- #endregion
- #region 属性
- public int ColumnIndex
- {
- get
- {
- return _columnIndex;
- }
- set
- {
- _columnIndex = value;
- }
- }
- public object Value
- {
- get
- {
- return _value;
- }
- set
- {
- _value = value;
- }
- }
- #endregion
- #region 构造函数
- public CsvConvertingEventArgs(int columnIndex, object value)
- {
- this.ColumnIndex = columnIndex;
- this.Value = value;
- }
- #endregion
- }
- #endregion
- }
|