Você está na página 1de 27

1. Handle the DataError event on the DataGridView.

If the context for the error is a commit operation, display the error in a
MessageBox.
private void dataGridView!DataError"o#$ect sender,
DataGridViewDataErrorEvent%rgs e&
'
(( If the data so)rce raises an exception when a cell val)e is
(( commited, display an error message.
if "e.Exception *+ n)ll ,,
e.-ontext ++ DataGridViewDataError-ontexts.-ommit&
'
MessageBox..how"/-)stomerID val)e m)st #e )ni0)e./&1
2
2
Sample Code
myComboBox.cs
// The NoKeyUpCombo class derives a new ComboBox whose WndProc
// method is overridden. This is reqired to address isses when
// !t is this derived combobox that is added to the data"rid.
// When yo T#B tro"h the $ata%rid and yo reach the $rop$own Combobox
// the &ocs is immediately moved to the next Colmn.
sin" 'ystem(
namespace #)adia.$ata%ridBondCombo
*
public class myComboBox: System.Windows.Forms.ComboBox
*
private const int W+,K-.UP / 0x101(
// The WndProc method corresponds exactly to the Windows
WindowProc 2nction.
// &or more in2ormation abot processin" Windows messa"es3 see
the WindowProc
// 2nction docmentation in the Windows Plat2orm '$K re2erence
located in
// the +'$N 4ibrary.
protected override void WndProc(ref
System.Windows.Forms.Messae t!eMessae"
*
// !"nore KeyUp event to avoid problem with tabbin" the
dropdown.
i2 5the+essa"e.+s" // W+,K-.UP6
*
retrn(
7
else
*
base.WndProc5re2 the+essa"e6(
7
7
7
7
DataGridComboBoxColumn.cs
sin" 'ystem(
sin" 'ystem.$ata(
sin" 'ystem.$rawin"(
sin" 'ystem.Windows.&orms(
namespace #)adia.$ata%ridBondCombo
*
public class #ata$ridComboBoxColumn : #ata$rid%extBoxColumn
*
pblic myComboBox myComboBox(
private 'ystem.Windows.&orms.Crrency+ana"er ,crrency+ana"er(
private int ,rowNm(
private bool ,-ditin"(
// Constrctor3 create or own cstomi8ed Combobox
pblic $ata%ridComboBoxColmn56
*
,crrency+ana"er / nll(
,-ditin" / 2alse(
// Create or own cstomi8ed Combobox3 which is sed in the
$ata%rid
// $rop$own4ist9 The ser cannot directly edit the text
portion.
// The ser mst clic) the arrow btton to
display the
// list portion.
// $rop$own9 The text portion is editable. The ser
mst clic)
// the arrow btton to display the list
portion.
// 'imple9 The text portion is editable. The list
portion is
// always visible.
myComboBox / new myComboBox56(
myComboBox.$rop$own'tyle / ComboBox'tyle.$rop$own4ist(
// +y own Combobox sbscribes to the 4eave -vent. !t occrs
when the
// inpt 2ocs leaves the ComboBox.
this.myComboBox.4eave :/
new 'ystem.-vent;andler54eaveComboBox6(
// +y own Combobox sbscribes to the
'electionChan"eCommitted -vent.
// !t occrs when the selected item has chan"ed and that
chan"e
// is committed 5save the chan"ed data to the $ata%rid
TextBox6.
this.myComboBox.'electionChan"eCommitted :/
new 'ystem.-vent;andler5'electionChan"eCommit6(
7
// +a)e crrent Combobox invisible when ser scrolls
// the $ata%rid control sin" the 'crollBar.
private void &andleScroll('b(ect sender) *vent+rs e"
*
i2 5myComboBox.<isible6
*
myComboBox.;ide56(
7
7
// The Colmn'tarted-ditin" method allows the $ata%rid
// to show a pencil in the row header indicatin" the row
// is bein" edited. 5base is the parent $ata%ridTextBoxColmn6
private void SelectionC!aneCommit('b(ect sender) *vent+rs e"
*
,-ditin" / tre(
base.Colmn'tarted-ditin"55'ystem.Windows.&orms.Control6
sender6(
7
// ;andle Combobox Behavior when &ocs leaves the Combobox.
private void ,eaveComboBox('b(ect sender) *vent+rs e"
*
i2 5,-ditin"6
*
// 'et the Combobox <ale+ember to the crrent =owColmn
// when the &ocs leaves the Combobox.
'etColmn<ale#t=ow5,crrency+ana"er3 ,rowNm3
myComboBox.Text6(
,-ditin" / 2alse(
// =edraws the colmn
!nvalidate56(
7
// ;ide the crrent Combobox when &ocs on Combobox is
loosen
myComboBox.;ide56(
// 4et crrent Combobox visible when ser scrolls
// the $ata%rid control sin" the 'crollBar.
this.$ata%ridTable'tyle.$ata%rid.'croll :/ new
'ystem.-vent;andler5;andle'croll6(
7
// The 'etColmn<ale#t=ow method pdates the bond
// $ataTable >Titles> with the <ale+ember
// 2or a "iven $isplay+ember / myComboBox.Text 2rom the
Combobox.
protected override void SetColumn-alue+t.ow
(CurrencyManaer source) int row/um) 'b(ect value"
*
?b@ect tb$isplay / vale(
$ata<iew dv / 5$ata<iew6this.myComboBox.$ata'orce(
int rowCont / dv.Cont(
int i / 0(
?b@ect cb$isplay(
?b@ect cb<ale(
// 4oop thro"h the Combobox $isplay+ember vales
// ntil yo 2ind the selected vale3 then read the
// <ale+ember 2rom the Combobox and pdate it in the
// $ataTable >Titles>
while 5i A rowCont6
*
cb$isplay / dvBiCBthis.myComboBox.$isplay+emberC(
i2 55cb$isplay D/ $BNll.<ale6 EE
5tb$isplay.-qals5cb$isplay666
*
brea)(
7
i :/ 1(
7
i2 5i A rowCont6
*
cb<ale / dvBiCBthis.myComboBox.<ale+emberC(
7
else
*
cb<ale / $BNll.<ale(
7
base.'etColmn<ale#t=ow5sorce3 rowNm3 cb<ale6(
7
// The %etColmn<ale#t=ow method pdates the bond
// Combobox with the $isplay+ember
// 2or a "iven =ow Nmber / rowNm 2rom the $ataTable >Titles>.
protected override 'b(ect $etColumn-alue+t.ow
(CurrencyManaer source) int row/um"
*
// %et the <ale+ember 2rom the $ataTable >Titles>
?b@ect tb<ale / base.%etColmn<ale#t=ow5sorce3 rowNm6(
// #ssociate a $ata<iew to the Combox3 so we can search
// the $isplay+ember in the Combox correspondin" to the
// <ale+ember 2rom the $ataTable >Titles>
$ata<iew dv / 5$ata<iew6this.myComboBox.$ata'orce(
int rowCont / dv.Cont(
int i / 0(
?b@ect cb<ale(
// 4oop thro"h the Combox -ntries and search the
$isplay+ember
while 5i A rowCont6
*
cb<ale / dvBiCBthis.myComboBox.<ale+emberC(
i2 55cb<ale D/ $BNll.<ale6 EE
5tb<ale D/ $BNll.<ale6 EE
5tb<ale.-qals5cb<ale666
*
brea)( // We 2ond the $isplay+ember F exit the 4oop
7
i :/ 1(
7
// !2 we are within the Combox -ntries3 retrn now the
$isplay+ember
// 2or the 2ond <ale+ember above. !2 we are at the -nd o2
the Combox
// -ntries3 retrn NU44
i2 5i A rowCont6
*
retrn dvBiCBthis.myComboBox.$isplay+emberC(
7
else
*
retrn $BNll.<ale(
7
7
// The -dit event is raised when the ser sets the 2ocs to the
cell
// containin" the combobox. !n this event the dimensions o2 the
combobox
// are set and an event handler is assi"ned to handle scrollin"
o2 the combobox.
protected override void *dit(
Crrency+ana"er sorce3
int rowNm3
=ectan"le bonds3
bool read?nly3
strin" instantText3
bool cell!s<isible6
*
base.-dit5sorce3 rowNm3 bonds3 read?nly3 instantText3
cell!s<isible6(
// 'et crrent =ownm and Postion +ana"er
,rowNm / rowNm(
,crrency+ana"er / sorce(
// Calclate 4ocation o2 the Combox relative to the TextBox
// o2 the $ata%rid which have the &ocs
Point New4oc(
New4oc / this.TextBox.4ocation(
New4oc.G F/ H(
New4oc.. F/ H(
myComboBox.4ocation / New4oc(
// #ttach the Combobox to the same Parent Control
// as the TextBox o2 the $ata%rid
myComboBox.Parent / this.TextBox.Parent(
// Position the Combox at the same 4ocation as the TextBox
myComboBox.'i8e / new 'i8e5this.TextBox.'i8e.Width : H3
myComboBox.'i8e.;ei"ht6(
// 'elect the -ntry in the Combobox correspondin" to the
Text in
// in the TextBox.
myComboBox.'elected!ndex /
myComboBox.&ind'trin"-xact5this.TextBox.Text6(
// myComboBox.Text / this.TextBox.Text(
// +a)e the TextBox invisible and then show the Combobox
this.TextBox.<isible / 2alse(
myComboBox.<isible / tre(
myComboBox.Brin"To&ront56(
myComboBox.&ocs56(
// +a)e Combobox invisible id User scrolls o or down the
$ata%rid
this.$ata%ridTable'tyle.$ata%rid.'croll :/ new
'ystem.-vent;andler5;andle'croll6(
7
// The Commit method can be sed to pt the Combomox <ale+ember
// into the TextBox <ale+ember. This can be handled in the
// 4eaveComboBox -vent;andler as well.
protected override bool Commit(
'ystem.Windows.&orms.Crrency+ana"er data'orce3int rowNm6
*
i2 5,-ditin"6
*
,-ditin" / 2alse(
'etColmn<ale#t=ow5data'orce3 rowNm3
myComboBox.Text6(
7
retrn tre(
7
7
7
Testapplication
sin" 'ystem(
sin" 'ystem.$rawin"(
sin" 'ystem.Collections(
sin" 'ystem.Component+odel(
sin" 'ystem.Windows.&orms(
sin" 'ystem.$ata(
sin" 'ystem.$ata.'qlClient(
namespace #)adia.$ata%ridBondCombo
*
public class #ata$ridBoundCombo : System.Windows.Forms.Form
*
private $ata'et ,$ata'et(
private 'qlConnection ,Conn(
private 'ql$ata#dapter ,$ata#dapterTitles(
private 'ql$ata#dapter ,$ata#dapterPblishers(
private 'ystem.Windows.&orms.$ata%rid ,$ata%rid(
private Crrency+ana"er ,crrency+ana"er(
private 'ystem.Windows.&orms.Btton btnUpdate(
private 'ystem.Windows.&orms.'tatsBar statsBar1(
private 'ystem.Windows.&orms.Btton btn$elete(
private 'ystem.Windows.&orms.Btton btnNew(
private 'ystem.Windows.&orms.Btton btnCancel(
private 'ystem.Component+odel.Container components / nll(
pblic $ata%ridBondCombo56
*
!nitiali8eComponent56(
7
protected override void $ispose5 bool disposin" 6
*
i25 disposin" 6
*
i2 5components D/ nll6
*
components.$ispose56(
7
7
base.$ispose5 disposin" 6(
7
.....
.....
0S%+%!read1
static void Main("
2
+pplication..un(new #ata$ridBoundCombo(""3
4
// !nitiali8in"
private void $ata%ridBondCombo,4oad5ob@ect sender3
'ystem.-vent#r"s e6
*
,$ata%rid.#llow'ortin" / 2alse(
%et$ata56(
7
// 4oad $ata 2rom the $atabase
private void $et#ata("
*
strin" strConn / >data
sorce/xeon(id/sa(password/mana"er(database/pbs>(
try
*
,Conn / new 'qlConnection5strConn6(
// &ill $ata'et
strin" str'I4 / >'-4-CT title3 title,id3 pb,id3 price
&=?+ Titles ?=$-= B. title>(
,$ata'et / new $ata'et56(
,$ata#dapterTitles / new 'ql$ata#dapter5str'I43 ,Conn6(
,$ata#dapterTitles.&ill5,$ata'et3 >Titles>6(
// Create an explicit UP$#T- command 2or the Titles
Table
,$ata#dapterTitles.UpdateCommand /
,Conn.CreateCommand56(
,$ata#dapterTitles.UpdateCommand.CommandText /
>UP$#T- Titles '-T >
: >title / J13 >
: >pb,id / JK3 >
: >price / JH >
: >W;-=- 5title,id / JL6>(
// #dd the parameters 2or UP$#T-
'qlParameter 1 / new
'qlParameter5>J1>3'ql$bType.<arChar3M03>title>6(
1.'orce<ersion / $ata=ow<ersion.Crrent(
,$ata#dapterTitles.UpdateCommand.Parameters.#dd516(
'qlParameter K / new
'qlParameter5>JK>3'ql$bType.Char3L3>pb,id>6(
K.'orce<ersion / $ata=ow<ersion.Crrent(
,$ata#dapterTitles.UpdateCommand.Parameters.#dd5K6(
'qlParameter H / new
'qlParameter5>JH>3'ql$bType.+oney303>price>6(
H.'orce<ersion / $ata=ow<ersion.Crrent(
,$ata#dapterTitles.UpdateCommand.Parameters.#dd5H6(
'qlParameter L / new
'qlParameter5>JL>3'ql$bType.Char3N3>title,id>6(
L.'orce<ersion / $ata=ow<ersion.?ri"inal(
,$ata#dapterTitles.UpdateCommand.Parameters.#dd5L6(
// Create an explicit !N'-=T command 2or the Titles
Table
,$ata#dapterTitles.!nsertCommand /
,Conn.CreateCommand56(
,$ata#dapterTitles.!nsertCommand.CommandText /
>!N'-=T !NT? titles 5title3 title,id3 pb,id3
price6 > :
><#4U-'5Ji13 JiK3 JiH3 JiL6>(
// #dd the parameters 2or !N'-=T
'qlParameter i1 / new
'qlParameter5>Ji1>3'ql$bType.<arChar3M03>title>6(
i1.'orce<ersion / $ata=ow<ersion.Crrent(
,$ata#dapterTitles.!nsertCommand.Parameters.#dd5i16(
'qlParameter iK / new
'qlParameter5>JiK>3'ql$bType.Char3N3>title,id>6(
iK.'orce<ersion / $ata=ow<ersion.Crrent(
,$ata#dapterTitles.!nsertCommand.Parameters.#dd5iK6(
'qlParameter iH / new
'qlParameter5>JiH>3'ql$bType.Char3L3>pb,id>6(
iH.'orce<ersion / $ata=ow<ersion.Crrent(
,$ata#dapterTitles.!nsertCommand.Parameters.#dd5iH6(
'qlParameter iL / new
'qlParameter5>JiL>3'ql$bType.+oney303>price>6(
iL.'orce<ersion / $ata=ow<ersion.Crrent(
,$ata#dapterTitles.!nsertCommand.Parameters.#dd5iL6(
// Create an explicit $-4-T- command 2or the Titles
Table
,$ata#dapterTitles.$eleteCommand /
,Conn.CreateCommand56(
,$ata#dapterTitles.$eleteCommand.CommandText /
>$-4-T- &=?+ titles > :
>W;-=- title,id / Jd1>(
// Bind parameters to appropriate colmns 2or $-4-T-
command
'qlParameter d1 / new
'qlParameter5>Jd1>3'ql$bType.Char3N3>title,id>6(
d1.'orce<ersion / $ata=ow<ersion.?ri"inal(
,$ata#dapterTitles.$eleteCommand.Parameters.#dd5d16(
// &ill a $ataTable 2or the bond ComboBox 5pblishers6.
//
// N?T-9 the ComboBox and "rid are N?T bond to the same
// table. !2 bond to the same table3 yo mst se
// di22erent bindin" contexts.
str'I4 / >'-4-CT pb,name3 pb,id &=?+ pblishers ?=$-=
B. pb,name>(
,$ata#dapterPblishers / new 'ql$ata#dapter5str'I43
,Conn6(
,$ata#dapterPblishers.&ill5,$ata'et3 >Pblishers>6(
7
catch 5-xception ex6
*
strin" ms" / ex.+essa"e.To'trin"56(
+essa"eBox.'how5ms"3 >Unable to retrieve data.>3
+essa"eBoxBttons.?K3 +essa"eBox!con.-rror6(
this.Close56(
retrn(
7
// Create a Table'tyle to 2ormat the data"ridOs colmns.
$ata%ridTable'tyle table'tyle / new $ata%ridTable'tyle56(
$ataTable dataTable / ,$ata'et.TablesB>Titles>C(
table'tyle.+appin"Name / >Titles>(
table'tyle.=ow;eaders<isible / tre(
table'tyle.=ow;eaderWidth / K0(
// Cstomi8e Colmns sin" own Colmn'tyle
2or 5int i / 0( i A dataTable.Colmns.Cont( i::6
*
switch 5i6
*
case 09 // title F mst correspond with >'-4-CT
title ...
$ata%ridTextBoxColmn colmn,0 / new
$ata%ridTextBoxColmn56(
colmn,0.+appin"Name / >title>(
colmn,0.;eaderText / >Title>(
colmn,0.Width / K00(
table'tyle.%ridColmn'tyles.#dd5colmn,06(
brea)(
case 19 // title,id F mst correspond with
>'-4-CT title ...
$ata%ridTextBoxColmn colmn,1 / new
$ata%ridTextBoxColmn56(
colmn,1.+appin"Name / >title,id>(
colmn,1.;eaderText / >!$>(
colmn,1.Width / 100(
table'tyle.%ridColmn'tyles.#dd5colmn,16(
brea)(
case K9 // pb,id F mst correspond with >'-4-CT
title ...
// Use a combobox 2or the pblisher.
$ata%ridComboBoxColmn colmn,K / new
$ata%ridComboBoxColmn56(
colmn,K.+appin"Name / >pb,id>(
colmn,K.;eaderText / >Pblisher>(
colmn,K.Width / 100(
colmn,K.myComboBox.$ata'orce /
,$ata'et.TablesB>Pblishers>C.$e2alt<iew(
colmn,K.myComboBox.$isplay+ember / >pb,name>(
colmn,K.myComboBox.<ale+ember / >pb,id>(
table'tyle.Pre2erred=ow;ei"ht /
colmn,K.myComboBox.;ei"ht(
table'tyle.%ridColmn'tyles.#dd5colmn,K6(
brea)(
case H9 // price F mst correspond with >'-4-CT
title ...
// Use a Property$escriptor to 2ormat colmn
Price.
Property$escriptorCollection pcol /
this.Bindin"Context
B,$ata'et3>Titles>C.%et!temProperties56(
$ata%ridTextBoxColmn colmn,H /
new $ata%ridTextBoxColmn5pcolB>price>C3
>c>3 tre6(
colmn,H.+appin"Name / >price>(
colmn,H.;eaderText / >Price>(
colmn,H.Width / 100(
table'tyle.%ridColmn'tyles.#dd5colmn,H6(
brea)(
de2alt9
$ata%ridTextBoxColmn TextCol / new
$ata%ridTextBoxColmn56(
TextCol.+appin"Name /
dataTable.ColmnsBiC.ColmnName(
TextCol.;eaderText / TextCol.+appin"Name(
TextCol.Width / 100(
table'tyle.%ridColmn'tyles.#dd5TextCol6(
brea)(
7
7
// #dd the cstom Tablestyle to the $ata"rid and bind the
// title Table data to the data"rid.
,$ata%rid.Table'tyles.Clear56(
,$ata%rid.Table'tyles.#dd5table'tyle6(
,$ata%rid.$ata'orce / dataTable(
// No addin" o2 new rows thro"h $ataview
,crrency+ana"er / 5Crrency+ana"er6this.Bindin"Context
B,$ata%rid.$ata'orce3 ,$ata%rid.$ata+emberC(
// 55$ata<iew6,crrency+ana"er.4ist6.#llowNew / 2alse(
statsBar1.Text / >$ata loaded.>(
7
// 'ave $ata to the $atabase F no Constrint Chec)in" is done
// to )eep code simple 2or thie demo.
private void btn5pdate6Clic7(ob(ect sender) System.*vent+rs e"
*
// $-BU%9 Print ot >Titles> Table in the $ata'et
// $ataTable aTable / ,$ata'et.TablesB>Titles>C(
// 2oreach5$ata=ow a=ow in aTable.=ows6
// *
// Console.Write4ine5a=owB>title,id>C.To'trin"56
// : >9 > : o=owB>pb,id>C.To'trin"566(
// 7
// Pendin" Chan"es P
i2 5,$ata'et.;asChan"es566
*
// Update the database
try
*
,$ata#dapterTitles.Update5,$ata'et3>Titles>6(
,$ata'et.#cceptChan"es56(
#pplication.$o-vents56(
statsBar1.Text / >Transaction5s6 sccess2lly
completed.>(
7
catch 5'ql-xception ex6
*
,$ata'et.=e@ectChan"es56(
+essa"eBox.'how5ex.+essa"e6(
7
7
else
*
statsBar1.Text / >No pendin" $ata to save.>(
7
7
// =eset 'tatsBar +essa"e
private void 6#ata$rid6CurrentCellC!aned(ob(ect sender)
System.*vent+rs e"
*
statsBar1.Text / >>(
7
// =etrn the selected =ows in an #rray4ist
public +rray,ist $etSelected.ows(#ata$rid d"
*
#rray4ist al / new #rray4ist56(
$ata<iew dv / 5$ata<iew6,crrency+ana"er.4ist(
2or5int i / 0( i A dv.Cont( ::i6
*
i2 5d".!s'elected5i66
*
al.#dd5i6(
7
7
retrn al(
7
// $elete selected =ows 2rom the $atabase3 show simple +essa"e.
// !n a real #pplication the User shol be as)ed be2ore the
// $elete #ction is per2ormed.
private void btn#elete6Clic7(ob(ect sender) System.*vent+rs e"
*
$ataTable aTable / ,$ata'et.TablesB>Titles>C(
strin" s / >$eleted =ows9 >(
i2 5%et'elected=ows5,$ata%rid6.Cont Q 06
*
2oreach5ob@ect o in %et'elected=ows5,$ata%rid66
*
$ata=ow a=ow / aTable.=owsB5int6oC(
a=ow.$elete56(
s :/ > > : o.To'trin"56(
7
// Update the database
try
*
,$ata#dapterTitles.Update5,$ata'et3>Titles>6(
,$ata'et.#cceptChan"es56(
#pplication.$o-vents56(
statsBar1.Text / s(
7
catch 5'ql-xception ex6
*
,$ata'et.=e@ectChan"es56(
+essa"eBox.'how5ex.+essa"e6(
7
7
else
*
statsBar1.Text / >No =ows selected 2or $eletion.>(
7
7
// Rmp to the last : 1 =ow and o22er a new created =ow
// to the User to enter a new Title.
private void btn/ew6Clic7(ob(ect sender) System.*vent+rs e"
*
// ,crrency+ana"er.#ddNew56(
,$ata%rid.CrrentCell / new
$ata%ridCell5,crrency+ana"er.Cont306(
statsBar1.Text / >Please enter new Title.>(
7
// =eload the $ata
private void btnCancel6Clic7(ob(ect sender) System.*vent+rs e"
*
i2 5this.,Conn D/ nll6
*
,Conn.Close56(
7
this.%et$ata56(
7
7
7
tao com#o#ox trong datagridview
To ComboBox trong DataGridView
31/10/2010 // No Comment // Categories: Advanced DOTNET.
Tn bi vit: To ComboBo trong Data!rid "ie#
Tc gi: $%ang.&T ' ()DN
Cp ! bi vit: C*+a ,-n* gi-
T"m t#t: To ComboBo trong Data!rid"ie#
$C% & VB'(et) To ComboBox trong DataGridView
C*.c c-c bn c/ng n*+ m0n* 1*i 23m vi4c v5i C)D6 ,7% s8 d9ng Data!rid"ie# ,: *i:n t*;
C)D6 n*+ng ,<i 1*i c-c bn 2i m%=n c-c ce22 b>n trong Data!rid"ie# 23 n*?ng Combobo ,:
ng@oi dAng cB t*: c*Cn n*?ng gi- tr; ,+Dc *i:n t*; b>n trong Combobo c*+ ,*-ng ./c n*0p
tr1c tip vo DataGridView. Ei7% n3F rGt cB 2Di 1*i bn m%=n r3ng b%Hc n*?ng gi- tr; ,+Dc
n*IJ v3o Data!rid"ie#.
)a% mHt t*Ki gian s%F ng*L v3 mi4t m3i 23m vi4c c%=i cAng m0n* c/ng t0m ,+Dc c-c* ,: to ra
c-c combobo trong Data!rid"ie#.
2' Cc *m c3n t*it
C-c bn *MF coJF c-c *3m cNn t*iOt sa% v3o ProQect
C%
interna2 static Data!rid"ie#ComboBoCo2%mn CreateComboboCo2%mnR)tring Co2%mnNameS
)tring TeaderTetS
DataTab2e JTab2eS )tring Co2%mnNameDisJ2aFU
V
Data!rid"ie#ComboBoCo2%mn obQCo2%mn W ne# Data!rid"ie#ComboBoCo2%mnRUX
obQCo2%mn.Name W Co2%mnNameX
obQCo2%mn.TeaderTet W TeaderTetX
obQCo2%mn.DataProJertFName W Co2%mnNameX
obQCo2%mn.DroJDo#nYidt* W 1Z0X
obQCo2%mn.Yidt* W 100X
obQCo2%mn.(aDroJDo#n&tems W 10X
obQCo2%mn.[2at)tF2e W [2at)tF2e.)tandardX
obQCo2%mn.Data)o%rce W JTab2eX
obQCo2%mn.DisJ2aF(ember W Co2%mnNameDisJ2aFX
ret%rn obQCo2%mnX
\
VB'(et
[riend )*ared [%nction CreateComboboCo2%mnRBF"a2 Co2%mnName As )tringS BF"a2
TeaderTet As )tringS BF"a2 JTab2e As DataTab2eS BF"a2 Co2%mnNameDisJ2aF As )tringU As
Data!rid"ie#ComboBoCo2%mn
Dim obQCo2%mn As Ne# Data!rid"ie#ComboBoCo2%mnRU
obQCo2%mn.Name W Co2%mnName
obQCo2%mn.TeaderTet W TeaderTet
obQCo2%mn.DataProJertFName W Co2%mnName
obQCo2%mn.DroJDo#nYidt* W 1Z0
obQCo2%mn.Yidt* W 100
obQCo2%mn.(aDroJDo#n&tems W 10
obQCo2%mn.[2at)tF2e W [2at)tF2e.)tandard
obQCo2%mn.Data)o%rce W JTab2e
obQCo2%mn.DisJ2aF(ember W Co2%mnNameDisJ2aF
]et%rn obQCo2%mn
End [%nction
4' Gii t*5c* cc t*am 67
Co2%mnName : T>n c^a co2%mn trong Data!rid"ie#
Teadtet: Tet s_ *i4n t*; tr>n Teader c^a Co2%mn
JTab2e : E=i t+Dng DataTab2e c*`a cHt gi- tr; cNn add v3o combobo
Co2%mnNameDisJ2aF : t>n c^a cHt trong DataTab2e m3 gi- tr; c^a cHt s_ ,+Dc *i:n t*; tr>n
ComboBo
8' Cc* 69 d:ng
"a d9 : Ta cB mHt DataTab2e b>n trong nB cB cHt b)TTc.
BdF giK ta m%=n add 2>n Data!rid"ie# mHt combobo co2%mn : nB cB t>n 23 b)TT)"cS J*Nn *i:n
t*; tr>n Teader 23 b)TT)":. Co2%mn n3F s_ 2GF d? 2i4% c^a cHt )TT trong DataTab2e
C%
Data!rid"ie#ComboBoCo2%mn obQCo2 W CreateComboboCo2%mnRb)TT)"cS b)TT)"cS
obQDataTab2eDan*sac*S b)TTcUX
data!rid"ie#1.Co2%mns.AddRobQCo2UX
VB
Dim obQCo2 As Data!rid"ie#ComboBoCo2%mn W CreateComboboCo2%mnRb)TT)"cS b)TT)"cS
obQDataTab2eDan*sac*S b)TTcU
data!rid"ie#1.Co2%mns.AddRobQCo2U
The following code example demonstrates how to use a DataGridView-om#oBox-ol)mn
to aid in entering data into the 3itle4f-o)rtesy column.
Copy
)sing .ystem1
)sing .ystem.Data1
)sing .ystem.Data..0l-lient1
)sing .ystem.5indows.6orms1
)sing .ystem.-ollections.Generic1
)sing .ystem.Drawing1
p)#lic class Employees 7 6orm
'
private DataGridView DataGridView + new DataGridView"&1
private DataGridView DataGridView8 + new DataGridView"&1
9.3%3hread:
p)#lic static void Main"&
'
try
'
%pplication.Ena#leVis)al.tyles"&1
%pplication.;)n"new Employees"&&1
2
catch "Exception e&
'
MessageBox..how"e.Message < e..tac=3race&1
2
2
p)#lic Employees"&
'
this.>oad <+ new EventHandler"6orm!>oad&1
2
private void 6orm!>oad".ystem.4#$ect sender, .ystem.Event%rgs e&
'
try
'
.et?p6orm"&1
.et?pDataGridView"&1
.et?pDataGridView8"&1
2
catch ".0lException&
'
MessageBox..how"/3he connection string @/
< connection.tring
< /A failed to connect. Modify it /
< /to connect to a Borthwind data#ase accessi#le to /
< /yo)r system./,
/E;;4;/, MessageBoxB)ttons.4C, MessageBoxIcon.Exclamation&1
%pplication.Exit"&1
2
2
private void .et?p6orm"&
'
.iDe + new .iDe"EFF, GFF&1
6low>ayo)tHanel flow>ayo)t + new 6low>ayo)tHanel"&1
flow>ayo)t.6lowDirection + 6lowDirection.3opDown1
flow>ayo)t.Doc= + Doc=.tyle.6ill1
-ontrols.%dd"flow>ayo)t&1
3ext + /DataGridView col)mns demo/1
flow>ayo)t.-ontrols.%dd"DataGridView&1
flow>ayo)t.-ontrols.%dd"DataGridView8&1
2
private void .et?pDataGridView8"&
'
DataGridView8.Doc= + Doc=.tyle.Bottom1
DataGridView8.3op>eftHeader-ell.Val)e + /.ales Details/1
DataGridView8.;owHeaders5idth.iDeMode +
DataGridView;owHeaders5idth.iDeMode.%)to.iDe3o%llHeaders1
2
private void .et?pDataGridView"&
'
DataGridView.DataError <+ new
DataGridViewDataErrorEventHandler"DataGridView!DataError&1
DataGridView.-ell-ontent-lic= <+ new
DataGridView-ellEventHandler"DataGridView!-ell-ontent-lic=&1
DataGridView.-ellVal)eH)shed <+ new
DataGridView-ellVal)eEventHandler"DataGridView!-ellVal)eH)shed&1
DataGridView.-ellVal)eBeeded <+ new
DataGridView-ellVal)eEventHandler"DataGridView!-ellVal)eBeeded&1
(( Virt)al mode is t)rned on so that the
(( )n#o)nd DataGridView-hec=Box-ol)mn will
(( =eep its state when the #o)nd col)mns are
(( sorted.
DataGridView.Virt)alMode + tr)e1
DataGridView.%)to.iDe + tr)e1
DataGridView.Data.o)rce + Hop)late"/.E>E-3 I 6;4M Employees/&1
DataGridView.3op>eftHeader-ell.Val)e + /Employees/1
DataGridView.;owHeaders5idth.iDeMode +
DataGridView;owHeaders5idth.iDeMode.%)to.iDe3o%llHeaders1
DataGridView.-ol)mnHeadersHeight.iDeMode +
DataGridView-ol)mnHeadersHeight.iDeMode.%)to.iDe1
DataGridView.%)to.iDe-ol)mnsMode +
DataGridView%)to.iDe-ol)mnsMode.%ll-ells1
DataGridView.%llow?ser3o%dd;ows + false1
DataGridView.%llow?ser3oDelete;ows + false1
(( 3he #elow a)togenerated col)mn is removed so
(( a DataGridView-om#o#ox-ol)mn co)ld #e )sed instead.
DataGridView.-ol)mns.;emove"-ol)mnBame.3itle4f-o)rtesy.3o.tring"&&1
DataGridView.-ol)mns.;emove"-ol)mnBame.;eports3o.3o.tring"&&1
%dd>in=-ol)mn"&1
%dd-om#oBox-ol)mns"&1
%ddB)tton-ol)mn"&1
%dd4)t4f4ffice-ol)mn"&1
2
private void %dd-om#oBox-ol)mns"&
'
DataGridView-om#oBox-ol)mn com#o#ox-ol)mn1
com#o#ox-ol)mn + -reate-om#oBox-ol)mn"&1
.et%lternate-hoices?singData.o)rce"com#o#ox-ol)mn&1
com#o#ox-ol)mn.Header3ext + /3itle4f-o)rtesy "via Data.o)rce property&/1
DataGridView.-ol)mns.Insert"F, com#o#ox-ol)mn&1
com#o#ox-ol)mn + -reate-om#oBox-ol)mn"&1
.et%lternate-hoices?singItems"com#o#ox-ol)mn&1
com#o#ox-ol)mn.Header3ext + /3itle4f-o)rtesy "via Items property&/1
(( 3ac= this example col)mn onto the end.
DataGridView.-ol)mns.%dd"com#o#ox-ol)mn&1
2
private void %dd>in=-ol)mn"&
'
DataGridView>in=-ol)mn lin=s + new DataGridView>in=-ol)mn"&1
lin=s.?se-ol)mn3ext6or>in=Val)e + tr)e1
lin=s.Header3ext + -ol)mnBame.;eports3o.3o.tring"&1
lin=s.DataHropertyBame + -ol)mnBame.;eports3o.3o.tring"&1
lin=s.%ctive>in=-olor + -olor.5hite1
lin=s.>in=Behavior + >in=Behavior..ystemDefa)lt1
lin=s.>in=-olor + -olor.Bl)e1
lin=s.3rac=Visited.tate + tr)e1
lin=s.Visited>in=-olor + -olor.JellowGreen1
DataGridView.-ol)mns.%dd"lin=s&1
2
private static void .et%lternate-hoices?singItems"
DataGridView-om#oBox-ol)mn com#o#ox-ol)mn&
'
com#o#ox-ol)mn.Items.%dd;ange"/Mr./, /Ms./, /Mrs./, /Dr./&1
2
private DataGridView-om#oBox-ol)mn -reate-om#oBox-ol)mn"&
'
DataGridView-om#oBox-ol)mn col)mn +
new DataGridView-om#oBox-ol)mn"&1
'
col)mn.DataHropertyBame + -ol)mnBame.3itle4f-o)rtesy.3o.tring"&1
col)mn.Header3ext + -ol)mnBame.3itle4f-o)rtesy.3o.tring"&1
col)mn.DropDown5idth + GF1
col)mn.5idth + KF1
col)mn.MaxDropDownItems + L1
col)mn.6lat.tyle + 6lat.tyle.6lat1
2
ret)rn col)mn1
2
private void .et%lternate-hoices?singData.o)rce"DataGridView-om#oBox-ol)mn
com#o#ox-ol)mn&
'
'
com#o#ox-ol)mn.Data.o)rce + ;etrieve%lternative3itles"&1
com#o#ox-ol)mn.Val)eMem#er + -ol)mnBame.3itle4f-o)rtesy.3o.tring"&1
com#o#ox-ol)mn.DisplayMem#er + com#o#ox-ol)mn.Val)eMem#er1
2
2
private Data3a#le ;etrieve%lternative3itles"&
'
ret)rn Hop)late"/.E>E-3 distinct 3itle4f-o)rtesy 6;4M Employees/&1
2
string connection.tring +
/Integrated .ec)rity+..HI1Hersist .ec)rity Info+6alse1/ <
/Initial -atalog+Borthwind1Data .o)rce+localhost/1
private Data3a#le Hop)late"string s0l-ommand&
'
.0l-onnection northwind-onnection + new .0l-onnection"connection.tring&1
northwind-onnection.4pen"&1
.0l-ommand command + new .0l-ommand"s0l-ommand,
northwind-onnection&1
.0lData%dapter adapter + new .0lData%dapter"&1
adapter..elect-ommand + command1
Data3a#le ta#le + new Data3a#le"&1
ta#le.>ocale + .ystem.Glo#aliDation.-)lt)reInfo.Invariant-)lt)re1
adapter.6ill"ta#le&1
ret)rn ta#le1
2
(( ?sing an en)m provides some a#straction #etween col)mn index
(( and col)mn name along with compile time chec=ing, and gives
(( a handy place to store the col)mn names.
en)m -ol)mnBame
'
EmployeeId,
>astBame,
6irstBame,
3itle,
3itle4f-o)rtesy,
BirthDate,
HireDate,
%ddress,
-ity,
;egion,
Hostal-ode,
-o)ntry,
HomeHhone,
Extension,
Hhoto,
Botes,
;eports3o,
HhotoHath,
4)t4f4ffice
21
private void %ddB)tton-ol)mn"&
'
DataGridViewB)tton-ol)mn #)ttons + new DataGridViewB)tton-ol)mn"&1
'
#)ttons.Header3ext + /.ales/1
#)ttons.3ext + /.ales/1
#)ttons.?se-ol)mn3ext6orB)ttonVal)e + tr)e1
#)ttons.%)to.iDeMode +
DataGridView%)to.iDe-ol)mnMode.%ll-ells1
#)ttons.6lat.tyle + 6lat.tyle..tandard1
#)ttons.-ell3emplate..tyle.Bac=-olor + -olor.Honeydew1
#)ttons.DisplayIndex + F1
2
DataGridView.-ol)mns.%dd"#)ttons&1
2
private void %dd4)t4f4ffice-ol)mn"&
'
DataGridView-hec=Box-ol)mn col)mn + new DataGridView-hec=Box-ol)mn"&1
'
col)mn.Header3ext + -ol)mnBame.4)t4f4ffice.3o.tring"&1
col)mn.Bame + -ol)mnBame.4)t4f4ffice.3o.tring"&1
col)mn.%)to.iDeMode +
DataGridView%)to.iDe-ol)mnMode.Displayed-ells1
col)mn.6lat.tyle + 6lat.tyle..tandard1
col)mn.3hree.tate + tr)e1
col)mn.-ell3emplate + new DataGridView-hec=Box-ell"&1
col)mn.-ell3emplate..tyle.Bac=-olor + -olor.Beige1
2
DataGridView.-ol)mns.Insert"F, col)mn&1
2
private void Hop)late.ales"DataGridView-ellEvent%rgs #)tton-lic=&
'
string employeeId + DataGridView.;ows9#)tton-lic=.;owIndex:
.-ells9-ol)mnBame.EmployeeId.3o.tring"&:.Val)e.3o.tring"&1
DataGridView8.Data.o)rce + Hop)late"/.E>E-3 I 6;4M 4rders 5HE;E
EmployeeId + / < employeeId&1
2
Mregion /.N> Error handling/
private void DataGridView!DataError"o#$ect sender,
DataGridViewDataErrorEvent%rgs anError&
'
MessageBox..how"/Error happened / < anError.-ontext.3o.tring"&&1
if "anError.-ontext ++ DataGridViewDataError-ontexts.-ommit&
'
MessageBox..how"/-ommit error/&1
2
if "anError.-ontext ++ DataGridViewDataError-ontexts.-)rrent-ell-hange&
'
MessageBox..how"/-ell change/&1
2
if "anError.-ontext ++ DataGridViewDataError-ontexts.Harsing&
'
MessageBox..how"/parsing error/&1
2
if "anError.-ontext ++ DataGridViewDataError-ontexts.>eave-ontrol&
'
MessageBox..how"/leave control error/&1
2
if ""anError.Exception& is -onstraintException&
'
DataGridView view + "DataGridView&sender1
view.;ows9anError.;owIndex:.Error3ext + /an error/1
view.;ows9anError.;owIndex:.-ells9anError.-ol)mnIndex:.Error3ext + /an
error/1
anError.3hrowException + false1
2
2
Mendregion
private void DataGridView!-ell-ontent-lic="o#$ect sender,
DataGridView-ellEvent%rgs e&
'
if "Is%BonHeader>in=-ell"e&&
'
Move3o>in=ed"e&1
2
else if "Is%BonHeaderB)tton-ell"e&&
'
Hop)late.ales"e&1
2
2
private void Move3o>in=ed"DataGridView-ellEvent%rgs e&
'
string employeeId1
o#$ect val)e + DataGridView.;ows9e.;owIndex:.-ells9e.-ol)mnIndex:.Val)e1
if "val)e is DBB)ll& ' ret)rn1 2
employeeId + val)e.3o.tring"&1
DataGridView-ell #oss + ;etrieve.)periors>astBame-ell"employeeId&1
if "#oss *+ n)ll&
'
DataGridView.-)rrent-ell + #oss1
2
2
private #ool Is%BonHeader>in=-ell"DataGridView-ellEvent%rgs cellEvent&
'
if "DataGridView.-ol)mns9cellEvent.-ol)mnIndex: is
DataGridView>in=-ol)mn ,,
cellEvent.;owIndex *+ O&
' ret)rn tr)e1 2
else ' ret)rn false1 2
2
private #ool Is%BonHeaderB)tton-ell"DataGridView-ellEvent%rgs cellEvent&
'
if "DataGridView.-ol)mns9cellEvent.-ol)mnIndex: is
DataGridViewB)tton-ol)mn ,,
cellEvent.;owIndex *+ O&
' ret)rn tr)e1 2
else ' ret)rn "false&1 2
2
private DataGridView-ell ;etrieve.)periors>astBame-ell"string employeeId&
'
foreach "DataGridView;ow row in DataGridView.;ows&
'
if "row.IsBew;ow& ' ret)rn n)ll1 2
if
"row.-ells9-ol)mnBame.EmployeeId.3o.tring"&:.Val)e.3o.tring"&.E0)als"employeeId&&
'
ret)rn row.-ells9-ol)mnBame.>astBame.3o.tring"&:1
2
2
ret)rn n)ll1
2
Mregion /chec=#ox state/
Dictionary@string, #oolA in4ffice + new Dictionary@string, #oolA"&1
private void DataGridView!-ellVal)eH)shed"o#$ect sender,
DataGridView-ellVal)eEvent%rgs e&
'
if "Is-hec=Box-ol)mn"e.-ol)mnIndex&&
'
string employeeId + GetCey"e&1
if "*in4ffice.-ontainsCey"employeeId&&
'
in4ffice.%dd"employeeId, "Boolean&e.Val)e&1
2
else
'
in4ffice9employeeId: + "Boolean&e.Val)e1
2
2
2
private string GetCey"DataGridView-ellVal)eEvent%rgs cell&
'
ret)rn DataGridView.;ows9cell.;owIndex:.
-ells9-ol)mnBame.EmployeeId.3o.tring"&:.Val)e.3o.tring"&1
2
private void DataGridView!-ellVal)eBeeded"o#$ect sender,
DataGridView-ellVal)eEvent%rgs e&
'
if "Is-hec=Box-ol)mn"e.-ol)mnIndex&&
'
string employeeId + GetCey"e&1
if "*in4ffice.-ontainsCey"employeeId&&
'
#ool defa)ltVal)e + false1
in4ffice.%dd"employeeId, defa)ltVal)e&1
2
e.Val)e + in4ffice9employeeId:1
2
2
private #ool Is-hec=Box-ol)mn"int col)mnIndex&
'
DataGridView-ol)mn o)t4f4ffice-ol)mn +
DataGridView.-ol)mns9-ol)mnBame.4)t4f4ffice.3o.tring"&:1
ret)rn "DataGridView.-ol)mns9col)mnIndex: ++ o)t4f4ffice-ol)mn&1
2
Mendregion
2
& am setting %J a DataGridView-om#oBox-ol)mn 2i1e t*is:
var new-ol)mn + new DataGridView-om#oBox-ol)mn"& '
Bame + /a#c/
21
new-ol)mn.Data.o)rce + new string9: ' /a/, /#/, /c/ 21
dgv.-ol)mns.%dd"new-ol)mn&1
T*is #or1s: eac* ro# *as a droJdo#n bo in t*at co2%mnS JoJ%2ated #it* aS bS c.
To#everS no# & #o%2d 2i1e to trim t*e 2ist eor certain ro#s. &fm trFing to set t*e 2ist Jer ro# 2i1e t*is:
foreach "DataGridView;ow row in dgv.;ows& '
var cell + "DataGridView-om#oBox-ell&"row.-ells9/a#c/:&1
cell.Data.o)rce + new string9: ' /a/, /c/ 21
2
To#everS t*is code *as no eeeect g everF ro# sti22 s*o#s hahS hbhS hch.
& *ave tried reJ2acing new string9: #it* new >ist@stringA and new Binding>ist@stringAS
bot* to no avai2.
& a2so *ave tried removing t*e code t*at sets new-ol)mn.Data.o)rceS b%t t*en t*e 2ists are
emJtF.
To# s*o%2d & go abo%t doing t*is JroJer2Fi
; do#n
vote accepted
T*e eo22o#ing #or1s eor me:
DataGridView-om#oBox-ol)mn new-ol)mn + new
DataGridView-om#oBox-ol)mn"&1
new-ol)mn.Bame + /a#c/1
new-ol)mn.Data.o)rce + new string9: ' /a/, /#/, /c/ 21
dataGridView.-ol)mns.%dd"new-ol)mn&1

foreach "DataGridView;ow row in dataGridView.;ows&
'
DataGridView-om#oBox-ell cell + "DataGridView-om#oBox-ell&
"row.-ells9/a#c/:&1
cell.Data.o)rce + new string9: ' /a/, /c/ 21
2
jo% co%2d a2so trF Rt*is a2so #or1s eor meU:
for "int row + F1 row @ dataGridView.-ol)mns.-o)nt1 row<<&
'
DataGridView-om#oBox-ell cell + "DataGridView-om#oBox-ell&
"dataGridView.;ows9row:.-ells9/a#c/:&1
cell.Data.o)rce + new string9: ' /f/, /g/ 21
2
Anot*er oJtion is to trF databinding on t*e ro# 2eve2. TrF %sing t*e event On]o#DataBo%nd
event. T*en Fo% can Jrogramatica22F set #*at is in t*e combo bo based on t*e contents oe t*at
ro#.
Oe co%rseS t*is Jres%mes Fo% are databinding Fo% grid.
/// AsmmaryQ
/// ;Sm tTo ra mUt VWi tXYn" $ata%rid<iew Combobox Colmn
/// A/smmaryQ
/// Aparam name/>varColmnName>QTZn c[a Colmn A/paramQ
/// Aparam name/>var;eaderText>QText s\ hi]n th^ _ Colmn
;eaderA/paramQ
/// AretrnsQA/retrnsQ
internal static $ata%rid<iewComboBoxColmn
2ncCreate$%<iewComboboxColmn5'trin" varColmnName3 'trin"
var;eaderText6
*
$ata%rid<iewComboBoxColmn ob@Colmn / new
$ata%rid<iewComboBoxColmn56(
ob@Colmn.Name / varColmnName(
ob@Colmn.;eaderText / var;eaderText(
ob@Colmn.$ataPropertyName / varColmnName(
ob@Colmn.=ead?nly / 2alse(
ob@Colmn.'orted / tre(
ob@Colmn.$rop$ownWidth / 1N0(
ob@Colmn.Width / 100(
ob@Colmn.+ax$rop$own!tems / 10(
ob@Colmn.&lat'tyle / &lat'tyle.'tandard(
retrn ob@Colmn(
7
/// AsmmaryQ
/// %`n $ata'ore cho $ata%rid<iewComboBoxColmn
/// A/smmaryQ
/// Aparam name/>ob@Comlmn>Q$ata%rid<iewComboBoxColmn can "`n
$ata 'orceA/paramQ
/// Aparam name/>ob@$atatable>Q$ataTable chba dc lid can
"`nA/paramQ
/// Aparam name/>varColmnName$isplay>QCUt s\ VXYc hi]n th^
trZn ComboboxA/paramQ
/// Aparam name/>varColmnName<ale>Q%i` tr^ tXen" bn" vfi c`c
phan tg tron" ComboboxA/paramQ
internal static void sb'et$ata'ore&or$%<iewComboboxColmn5re2
$ata%rid<iewComboBoxColmn ob@Comlmn3
$ataTable ob@$atatable3 'trin"
varColmnName$isplay3 'trin" varColmnName<ale6
*
ob@Comlmn.$ata'orce / ob@$atatable(
ob@Comlmn.$isplay+ember / varColmnName$isplay(
ob@Comlmn.<ale+ember / varColmnName<ale(
7
Cch s dng
Visual C# Code:
La chn code | n/Hin code
//TTo Colmn 'TT dTn" Combobox
$ata%rid<iewComboBoxColmn ob@Colmn /
2ncCreate$%<iewComboboxColmn5>'TT>3 >'TT>6(
//%`n $ata'ore cho Combobox3 phan hi]n th^ vS phan "i` tr^ tXen" bn"
Vh lS c[a cUt 'TT
sb'et$ata'ore&or$%<iewComboboxColmn5ob@Colmn3 ob@$ataTable$anhsach3
>'TT>3 >'TT>6(
//#dd cUt vSo $ata"ridview
$%$anhsach'<.Colmns.#dd5ob@Colmn6(
Hi all!
Cui cng th mnh cng d tm ra vn d ny v kip nap bi cho thy gio.
Trong datagridview cc ban nn ch ti 2 thuc tnh
DatagridviewComboBoxColumn v DtgridviewComboboxCell, c th hiu nhu l cc
combobox mt ct v mt hng no d.
Nhu vy d gn gi tri hin thi "tn hng" trong combobox tai mt no d, cc
ban ch cn st
DataGridViewComboBoxCell cell =
DataGridViewComboBoxCell)grdData.Rows[i].Cells["TenHang"];
cell.OwningRow.Cells["TenHang"].Value =
grdData.Rows[i].Cells["MaHang"].Value.ToString();
Gi d ta c 2 ct m hng v tn hng
Lm nhu trn cc ban s ging dng gia m hng v tn hng. Vn d ny lm
trong winform kh hon webform.
Vn v combobox trong datagridview
mnh c doan code sau:
String sSelect = " Select * from HANG_HOA";
SqlDataAdapter sqlArd = new SqlDataAdapter(sSelect, clsConn.sqlCNN);
DataTable tableSP = new DataTable();
sqlArd.Fill(tableSP);
dataGridView1.DataSource = tableSP;
dataGridView1.Columns.Clear();
DataGridViewComboBoxColumn col0 = new DataGridViewComboBoxColumn();
col0.HeaderText = "Tn sn phm";
col0.DataSource = tableSP;
col0.DisplayMember = "TenHangHoa";
col0.ValueMember = "MaHangHoa";
col0.DataPropertyName = "MaHangHoa";
col0.Name = "TenHangHoa";
dataGridView1.Columns.AddRange(new DataGridViewComboBoxColumn[]{col0});
mnh tao 1 combobox trong datagridview d hin thi tn sn phm. Khi chay th n
t dng din cc Item trong ct TenHangHoa vo cc row trong ct Tn sn phm
ch khng hin thi cc item trong 1 combobox.
co cn thm thuc tnh g na khng?
mnh gip ban insert thi, cn dua checkbox, textbox vo ban phi t tm
hiu cc Property ca dataGridView, nhu th mi c th quen duoc. V ban
chua cho bit chn vo bng no nn mnh minh ha ban thay lai nh
//--------insert-------------
try
{
string ChuoiKetNoi="";//dua vao chuoi ket noi cua ban
SqlConnection connect=new SqlConnection(ChuoiKetNoi);
string insert="insert into TenBang values (' "+textbox1.text+" ','
"+textbox2.text+" ') ";
SqlCommand command=new SqlCommand(insert,connect);
command.exeNonQuery...();//Khng cn gi tri tr v
connect.close();
connect.dispose();
}
catch(Exception ex)
{
messageBox.show(ex.message);
}
C
// 'et $ata%rid<iew Combo Colmn 2or Car!$ 2ield
$ata%rid<iewComboColmn ColmnCar / new $ata%rid<iewComboColmn56
(
// $ata%rid<iew Combo <ale+ember 2ield name is >Car!$>
// $ata%rid<iew Combo $isplay+ember 2ield name is >Car>
ColmnCar.$ataPropertyName / >Car!$>(
ColmnCar.;eaderText / >Car Name>(
ColmnCar.Width / M0(
// Bind ColmnCar to Cars table
ColmnCar.box.$ata'orce / ds.TablesB>Cars>C(
ColmnCar.box.<ale+ember / >Car!$>(
ColmnCar.box.$isplay+ember / >Car>(
// #dd ColmnCar onto $ata%rid<iew layot
$ata%rid<iew1.Colmns.#dd5ColmnCar6(
Combobox, CheckBox inside DataGridView
Mnh ko th DataGridView vo Form ri sau d chut phi chn Edit, tao ra Column
dang Combobox tn cbb, Column dang TextBox tn txt, Column dang CheckBox tn
chk.
Sau d trong code cho
Code:
foreach(DataRow dr in DataTable.Row)
{
DataGridView.Rows.Add(dr[dr.ItemArray]);
}
cbb.DataSource = DataTable;
cbb.DisplayMenber = ColumnName;
cbb.ValueMember = ColumnName;
----------------------------------------Mnh d lm nhu th-------------------
Gi mnh mun Column Combobox, CheckBox fi tao t code ch ko fi Edit bng
tay.
ng thi cc ban gip mnh cch x l sau khi din thng tin trc tip th s add
vo CSDL lun nh!
Thanks!

Você também pode gostar