欢迎光临
我们一直在努力

DataGrid常见关注问题解决方案-.NET教程,数据库应用

建站超值云服务器,限时71元/月

introduction

the datagrid web server control is a powerful tool for displaying information from a data source. it is easy to use; you can display editable data in a professional-looking grid by setting only a few properties. at the same time, the grid has a sophisticated object model that provides you with great flexibility in how you display the data.

this paper addresses some of the questions about customizing grid display that are commonly asked in newsgroups, on web sites, and in other developer forums. the techniques described here are sometimes quite simple and at other times somewhat involved. in each case, however, they address a question of how to go beyond the basic functionality of the datagrid control.

this paper assumes that you are already familiar with the control — how to add it to a form and configure it to display data. you should also understand how to put a row in the grid into edit mode and other basic tasks. (for details, see datagrid web server control.) finally, you will find it helpful to know how to work with templates — adding template columns to the grid and layout out controls inside a template.

windows forms versus web forms datagrid control

the web forms datagrid control is not the same as the windows forms equivalent. it is a common (and not unreasonable) assumption that they are the same control, or at least have identical functionality. however, the entire programming paradigm for web forms is quite different from that for windows forms. for example, web forms pages perform a round trip to the server for any processing; they must manage state; they feature a very different data-binding model; and so on.

because of these differences, there are also significant differences in their respective controls, including the datagrid control. as a general rule, the web forms datagrid control includes less built-in functionality. a few examples of differences in the web forms datagrid control are:

it does not inherently support master-detail data structures.

as with other web server controls, it does not support two-way data binding. if you want to update data, you must write code to do this yourself.

you can only edit one row at a time.

it does not inherently support sorting, although it raises events you can handle in order to sort the grid contents.

on the other hand:

you can bind the web forms datagrid to any object that supports the ienumerable interface.

the web forms datagrid control supports paging.

it is easy to customize the appearance and layout of the web forms datagrid control as compared to the windows forms one. (details are provided later in this paper.)

controlling column width, height, and alignment

by default, the datagrid control sizes rows and columns to fit the overall height and width that you have assigned to the grid. within the overall grid width, it sizes columns according to the width of the column heading text. all data is displayed left-justified by default.

to control column characteristics, you should turn off auto column generation by setting the autogeneratecolumns property to false. in fact, you should set this property to true only for short-term uses, such as quick proof-of-concept pages or demonstrations. for production applications, you should add columns explicitly. the individual columns can be bound columns or template columns.

to set the column width, you create a style element for that column and then set the elements width property to standard units (say, pixels). the following example shows you what the html syntax looks like for an itemstyle element with its width property set.

<asp:boundcolumn datafield="title" sortexpression="title"

headertext="title">

<itemstyle width="100px"></itemstyle>

</asp:boundcolumn>

alternatively, you can do the same thing by setting the itemstyle property directly in the element, as in the following example:

<asp:boundcolumn itemstyle-width="100px" datafield="title"

sortexpression="title" headertext="title">

</asp:boundcolumn>

you can set alignment using the style element, setting it to "right," "left," and other values defined in the horizontalalign enumeration. (in visual studio, alignment is available for individual columns in the format tab of the grids property builder.) the following is an example:

<asp:boundcolumn datafield="title" sortexpression="title"

headertext="title">

<itemstyle width="100px" horizontalalign="right"></itemstyle>

</asp:boundcolumn>

you can also set a columns height using the style element (or the itemstyle-height property). you will probably find this less flexible than setting the width, since setting the height for one column sets it for all of them.

you can set the width in code at run time as well. one place to do so is in an itemcreated event handler. the following example sets the width of the first two columns to 100 and 50 pixels, respectively:

visual basic

private sub datagrid1_itemcreated(byval sender as object, _

byval e as system.web.ui.webcontrols.datagriditemeventargs) _

handles datagrid1.itemcreated

e.item.cells(0).width = new unit(100)

e.item.cells(1).width = new unit(50)

end sub

// c#

private void datagrid1_itemcreated(object sender,

system.web.ui.webcontrols.datagriditemeventargs e)

{

e.item.cells[0].width = new unit(100);

e.item.cells[1].width = new unit(50);

}

of course, there is little sense in setting a fixed width in code that you could set at design time. you would normally do this only if you wanted to set the width based on a run-time value. you can set the width of a cell or control in units (typically pixels), but it is not straightforward to translate the length of data — which is simply a character count — into pixels. but the data is available for you to examine when you are creating the item.

customizing column layout in display and edit mode

by default, the grid displays data in pre-sized columns. when you put a row into edit mode, the control displays text boxes for all editable data, regardless of what data type the data is.

if you want to customize the content of a column, make the column a template column. template columns work like item templates in the datalist or repeater control, except that you are defining the layout of a column rather than a row.

when you define a template column, you can specify the following template types:

the itemtemplate allows you to customize the normal display of the data.

the edititemtemplate allows you to specify what shows up in the column when a row is put into edit mode. this is how you can specify a control other than the default text box for editing.

a headertemplate and footertemplate allow you to customize the header and footer, respectively. (the footer is only displayed if the grids showfooter property is true.)

the following example shows the html syntax for a template column that displays boolean data. both the itemtemplate and edititemtemplate use a check box to display the value. in the itemtemplate, the check box is disabled so that users do not think they can check it. in the edititemtemplate, the check box is enabled.

<columns>

<asp:templatecolumn headertext="discontinued">

<itemtemplate>

<asp:checkbox runat="server" enabled= false name ="checkbox2"

id="checkbox2"

checked = <%# databinder.eval(container,

"dataitem.discontinued") %> >

</asp:checkbox>

</itemtemplate>

<edititemtemplate>

<asp:checkbox

runat="server" name ="checkbox2" id="checkbox2"

checked = <%# databinder.eval(container,

"dataitem.discontinued") %> >

</asp:checkbox>

</edititemtemplate>

</asp:templatecolumn>

</columns>

note if you use a checkbox control in the edititemtemplate, be aware that at run time, the grid cell actually contains several literalcontrol controls (for spacing) in addition to the check box itself. whenever you know the id of the control whose value you want, use the findcontrol method to create a reference to it, rather than using specific indexes into the cells and controls collections:

visual basic

dim cb as checkbox

cb = ctype(e.item.findcontrol("checkbox2"), checkbox)

// c#

checkbox cb;

cb = (checkbox) e.item.findcontrol("checkbox2");

in visual studio, you can use the grids property builder to create the template column and use the template editor to specify the layout. in the columns tab of the properties window page for the grid, select the column and at the bottom, click convert this column into a template column. close the properties window, right-click the grid, and choose edit template. you can then drag controls from the toolbox into the template and add static text.

formatting dates, currency, and other data

information in a datagrid control is ultimately displayed in an html table in the web forms page. to control how data is displayed, therefore, you can specify .net string formatting for column values. you cannot specify formatting for columns generated when the grids autogeneratecolumns property is set to true, only for bound or template columns.

to format, set the columns dataformatstring property to a string-formatting expression suitable for the data type of the data you are formatting. a slightly confusing aspect of format strings is that the same specifier — for example, "d" — can be applied to different data types (integers, dates) with different results.

note in visual studio, you can specify a formatting expression in the columns tab of the controls property builder.

some example formatting strings are listed in the following table. for more information, see the topics formatting types and boundcolumn.dataformatstring property in the visual studio documentation.

format expression applied to this data type description

price: {0:c}

note the {0} is a zero, not the letter o. numeric/decimal displays the literal "price:" followed by numbers in currency format. the currency format depends on the culture setting specified via the culture attribute on the page directive or in the web.config file.

{0:d4} integer (cannot be used with decimal numbers.) integers are displayed in a zero-padded field four characters wide.

{0:n2}% numeric displays the number with 2-decimal place precision followed by the literal "%".

{0:000.0} numeric/decimal numbers rounded to one decimal place. numbers less than three digits are zero padded.

{0:d} date/datetime long date format ("thursday, august 06, 1996"). date format depends on the culture settting of the page or the web.config file.

{0:d} date/datetime short date format ("12/31/99").

{0:yy-mm-dd} date/datetime date in numeric year-month-day format (96-08-06).

showing and hiding columns dynamically

one way to have columns appear dynamically is to create them at design time, and then to hide or show them as needed. you can do this by setting a columns visible property. the following example shows how to toggle the visibility of the second column (index 1) of the grid:

visual basic

datagrid1.columns(1).visible = not (datagrid1.columns(1).visible)

// c#

datagrid1.columns[1].visible = !(datagrid1.columns[1].visible);

adding columns dynamically

you can hide and show columns if you know in advance what columns you need. sometimes, however, you do not know that until run time. in that case, you can create columns dynamically and add them to the grid.

to do so, you create an instance of one of the column classes supported by the grid — boundcolumn, editcommandcolumn, buttoncolumn, or hyperlinkcolumn. (you can add template columns to the grid, but it is slightly more complex. for details, see creating web server control templates programmatically.) set the columns properties, and then add it to the grids columns collection.

the following example shows how to add two bound columns to a grid.

visual basic

private sub button1_click(byval sender as system.object, _

byval e as system.eventargs) handles button1.click

set data-binding properties of the grid

datagrid1.autogeneratecolumns = false

datagrid1.datasource = me.dsbooks1

datagrid1.datamember = "books"

datagrid1.datakeyfield = "bookid"

add two columns

dim dgc_id as new boundcolumn()

dgc_id.datafield = "bookid"

dgc_id.headertext = "id"

dgc_id.itemstyle.width = new unit(80)

datagrid1.columns.add(dgc_id)

dim dgc_title as new boundcolumn()

dgc_title.datafield = "title"

dgc_title.headertext = "title"

datagrid1.columns.add(dgc_title)

me.sqldataadapter1.fill(me.dsbooks1)

datagrid1.databind()

end sub

// c#

private void button1_click(object sender, system.eventargs e)

{

datagrid1.autogeneratecolumns = false;

datagrid1.datasource = this.dsbooks1;

datagrid1.datamember = "books";

datagrid1.datakeyfield = "bookid";

// add two columns

boundcolumn dgc_id = new boundcolumn();

dgc_id.datafield = "bookid";

dgc_id.headertext = "id";

dgc_id.itemstyle.width = new unit(80);

datagrid1.columns.add(dgc_id);

boundcolumn dgc_title= new boundcolumn();

dgc_title.datafield = "title";

dgc_title.headertext = "title";

datagrid1.columns.add(dgc_title);

this.sqldataadapter1.fill(this.dsbooks1);

datagrid1.databind();

}

any time that you add controls to a page dynamically, you have the problem of persistence. dynamically-added controls (or in this case, columns) are not automatically added to the pages view state, so you are obliged to add logic to the page to make sure the columns are available with each round trip.

an excellent way to do this is to override the pages loadviewstate method, which gives you an early opportunity to reestablish columns in the datagrid control. because the loadviewstate method is called before the page_load event is raised, re-adding columns in the loadviewstate method assures that they are available for normal manipulation by the time any event code runs.

the following example shows how you would expand the previous example to restore the columns each time the page runs again. as before, the button1_click handler adds two columns to the grid. (in this example, the event handler calls a separate routine called addcolumns to do so.) in addition, the page contains a simple boolean property called dynamiccolumnsadded indicating whether the grid has had columns added; the property persists its value in view state. the loadviewstate method first calls the base classs loadviewstate method, which extracts view state information and configures controls with it. if columns were previously added to the grid (as per the dynamiccolumnsadded property), the method then re-adds them.

visual basic

private property dynamiccolumnadded() as boolean

get

if viewstate("columnadded") is nothing then

return false

else

return true

end if

end get

set(byval value as boolean)

viewstate("columnadded") = value

end set

end property

protected overrides sub loadviewstate(byval savedstate as object)

mybase.loadviewstate(savedstate)

if me.dynamiccolumnadded then

me.addcolums()

end if

end sub

private sub button1_click(byval sender as system.object, _

byval e as system.eventargs) handles button1.click

check property to be sure columns are not added more than once

if me.dynamiccolumnadded then

return

else

me.addcolums()

end if

end sub

protected sub addcolums()

add two columns

dim dgc_id as new boundcolumn()

dgc_id.datafield = "instock"

dgc_id.headertext = "in stock?"

dgc_id.itemstyle.width = new unit(80)

datagrid1.columns.add(dgc_id)

dim dgc_title as new boundcolumn()

dgc_title.datafield = "title"

dgc_title.headertext = "title"

datagrid1.columns.add(dgc_title)

me.datagrid1.databind()

me.dynamiccolumnadded = true

end sub

// c#

private bool dynamiccolumnadded{

get

{

object b = viewstate["dynamiccolumnadded"];

return (b == null) ? false : true;

}

set

{

viewstate["dynamiccolumnadded"] = value;

}

}

protected override void loadviewstate(object savedstate)

{

base.loadviewstate(savedstate);

if (dynamiccolumnadded)

{

this.addcolumns();

}

}

private void button1_click(object sender, system.eventargs e)

{

if(this.dynamiccolumnadded != true)

{

this.addcolumns();

}

}

private void addcolumns()

{

boundcolumn dgc_id = new boundcolumn();

dgc_id.datafield = "bookid";

dgc_id.headertext = "id";

dgc_id.itemstyle.width = new unit(80);

datagrid1.columns.add(dgc_id);

boundcolumn dgc_title= new boundcolumn();

dgc_title.datafield = "title";

dgc_title.headertext = "title";

datagrid1.columns.add(dgc_title);

this.sqldataadapter1.fill(this.dsbooks1);

datagrid1.databind();

this.dynamiccolumnadded = true;

}

adding new records to a data source using the datagrid control

the datagrid control allows users to view and edit records, but does not inherently include the facility to add new ones. however, you can add this functionality in various ways, all of which involve the following:

adding a new, blank record to the data source of the grid (in the dataset or database). if necessary, you will need to assign an id for the record and put placeholder values into it for any columns that cannot be null.

rebinding the datagrid control to the source.

putting the grid into edit mode for the new record. you need to be able to determine where in the grid the new record appears.

updating the record normally when the user clicks update, thereby writing the new record to the source with user-provided values.

the following example shows the process for adding the new record, binding the grid, and putting it into edit mode. in this example, the data source is a dataset (dsbooks1 or dsbooks1) containing a table called "books."

visual basic

private sub btnaddrow_click(byval sender as system.object, _

byval e as system.eventargs) handles btnaddrow.click

dim dr as datarow = me.dsbooks1.books.newrow

dr("title") = "(new)"

dr("instock") = true

me.dsbooks1.books.rows.insertat(dr, 0)

session("dsbooks") = dsbooks1

datagrid1.edititemindex = 0

datagrid1.databind()

end sub

// c#

private void btnaddrow_click(object sender, system.eventargs e)

{

datarow dr = this.dsbooks1.books.newrow();

dr["title"] = "(new)";

dr["instock"] = true;

this.dsbooks1.books.rows.insertat(dr, 0);

session["dsbooks"] = dsbooks1;

datagrid1.edititemindex = 0;

datagrid1.databind();

}

some things to notice:

this code runs when a user clicks an add button somewhere in the page.

the new row is created using the newrow method. it is then inserted into the dataset table using the insertat method, which allows you to place it at a specific, predefined location — in this case, as the first record in the table (that is, the first record in the rows collection). alternatively, you could add it to the end of the table, using the row count as the value. the important thing is that you know exactly where the row is in the table.

because you know that the record is in the first position of the table, you can set the grids edititemindex value to zero to put the new row into edit mode. (if you created the row elsewhere in the table, you would set edititemindex to that location instead.)

because you have a new record in the dataset (but not yet in the database), you have to keep a copy of the dataset between round trips — you do not want to refill it from the database and lose the new record. here, the code stores it in session state. you need to reload the dataset from session state when the page loads. the following example shows what your page_load handler might look like:

visual basic

private sub page_load(byval sender as system.object, _

byval e as system.eventargs) handles mybase.load

if me.ispostback then

dsbooks1 = ctype(session("dsbooks"), dsbooks)

else

me.sqldataadapter1.fill(me.dsbooks1)

session("dsbooks") = dsbooks1

datagrid1.databind()

end if

end sub

// c#

private void page_load(object sender, system.eventargs e)

{

if(this.ispostback)

{

dsbooks1 = (dsbooks) session["dsbooks"];

}

else

{

this.sqldataadapter1.fill(this.dsbooks1);

session["dsbooks"] = dsbooks1;

this.datagrid1.databind();

}

}

for information about maintaining state, see web forms state management in the visual studio documentation.

you can update the record normally. for an example, see walkthrough: using a datagrid web control to read and write data in the visual studio documentation. after updating the dataset, update the database, then refresh the dataset. be sure to save the refreshed dataset to session state again. here is an example of an update handler:

visual basic

private sub datagrid1_updatecommand(byval source as object, _

byval e as system.web.ui.webcontrols.datagridcommandeventargs) _

handles datagrid1.updatecommand

dim dr as dataset.booksrow

get a reference to row zero (where the row was inserted)

dr = me.dsbooks1.books(0)

dim tb as textbox = ctype(e.item.cells(2).controls(0), textbox)

dr.title = tb.text

dim cb as checkbox = ctype(e.item.cells(3).controls(1), checkbox)

dr.instock = cb.checked

me.sqldataadapter1.update(me.dsbooks1)

datagrid1.edititemindex = -1

refresh the dataset from the database

dsbooks1.clear()

me.sqldataadapter1.fill(me.dsbooks1)

save the refreshed dataset in session state agin

session("dsbooks") = dsbooks1

datagrid1.databind()

end sub

// c#

private void datagrid1_updatecommand(object source,

system.web.ui.webcontrols.datagridcommandeventargs e)

{

dsbooks.booksrow dr;

//get a reference to row zero (where the row was inserted)

dr = this.dsbooks1.books[0];

textbox tb1 = (textbox) e.item.cells[2].controls[0];

dr.title = tb1.text;

checkbox cb = (checkbox) e.item.cells[3].controls[1];

dr.instock = cb.checked;

this.sqldataadapter1.update(this.dsbooks1);

datagrid1.edititemindex = -1;

//refresh the dataset from the database

dsbooks1.clear();

this.sqldataadapter1.fill(this.dsbooks1);

//save the refreshed dataset in session state agin

session["dsbooks"] = dsbooks1;

datagrid1.databind();

}

displaying a drop-down list in edit mode

a common request is to present users with a drop-down list when a row is in edit mode. for example, the grid might show a list of books, including each books genre. when users edit a book record, they might want to assign a different genre; ideally, they can select from a drop-down list that shows possible genre values such as "fiction," "biography," or "reference."

displaying a drop-down list requires a template column in the grid. typically, the itemtemplate contains a control such as a data-bound label control to show the current value of a field in the record. you then add a drop-down list to the edititemtemplate. in visual studio, you can add a template column in the property builder for the grid, and then use standard template editing to remove the default textbox control from the edititemtemplate and drag a dropdownlist control into it instead. alternatively, you can add the template column in html view.

after you have created the template column with the drop-down list in it, there are two tasks. the first is to populate the list. the second is to preselect the appropriate item in the list — for example, if a books genre is set to "fiction," when the drop-down list displays, you often want "fiction" to be preselected. (preselecting an item might not be an issue in all scenarios.)

there are many ways to populate the drop-down list. the following examples show you three possibilities: using static items; using records from a dataset; or by using a data reader to read information directly from a database.

static items

to display static items in the drop-down list, you do not data bind the control. instead, you simply define items in the controls items collection. in visual studio, you can invoke the items collection editor from the items property in the properties window. alternatively, you can add items in html view.

the following shows a complete column definition for a template column that displays the genre in display mode, and a static list of genre types in edit mode. the itemtemplate contains a label control whose text property is bound to the "genre" field of the current record. the declarations for the static items in the edititemtemplate are highlighted.

<asp:templatecolumn headertext="genre">

<itemtemplate>

<asp:label id=label4 runat="server"

text=<%# databinder.eval(container, "dataitem.genre") %>>

</asp:label>

</itemtemplate>

<edititemtemplate>

<asp:dropdownlist id="dropdownlist2" runat="server" width="172px">

<asp:listitem value="fiction">fiction</asp:listitem>

<asp:listitem value="biography">biography</asp:listitem>

<asp:listitem value="reference">reference</asp:listitem>

</asp:dropdownlist>

</edititemtemplate>

</asp:templatecolumn>

dataset

if the data you want to display in the drop-down list is in a dataset, you can use ordinary data binding. the following shows the declarative syntax. the dropdownlist control is bound to the genre table in a dataset called dsbooks1. the data-binding settings are highlighted.

<asp:templatecolumn headertext="genre (dataset)">

<itemtemplate>

<asp:label id=label3 runat="server"

text=<%# databinder.eval(container, "dataitem.genre") %>>

</asp:label>

</itemtemplate>

<edititemtemplate>

<asp:dropdownlist id=dropdownlist4 runat="server"

datasource="<%# dsbooks1 %>" datamember="genre"

datatextfield="genre" datavaluefield="genre" width="160px">

</asp:dropdownlist>

</edititemtemplate>

</asp:templatecolumn>

data reader

you can also populate the drop-down list directly from a database. this method is more involved, but it can be more efficient, since you do not actually read the data from the database till the moment you need it.

a relatively easy way to do this is to take advantage of web forms data-binding expressions. although it is most common to call the databinder.eval method in a data-binding expression, you can in fact call any public member available to the page. this example shows you how to create a function that creates, fills, and returns a datatable object that the drop-down list can bind to.

for this scenario, you will need to be able to execute a data command that gets the records you want. for example, you might define a data command whose commandtext property is select * from genres. to simplify the example, it will be assumed that you have a connection object and a data command object already on the page.

start by creating a public function in the page that creates a data table object and defines the columns you need in it. then open the connection, execute the data command to return a data reader, and loop through the reader, copying the data to the table. finally, return the table as the functions return value.

the following example shows how you can do this. in this case, there is only one column in the returned table ("genre"). when you populate a drop-down list, you usually need only one column, or two columns if you want to set the drop-down lists text and values to different columns.

visual basic

public function getgenretable() as datatable

dim dtgenre as datatable = new datatable()

if application("genretable") is nothing then

dim dr as datarow

dim dc as new datacolumn("genre")

dtgenre.columns.add(dc)

me.sqlconnection1.open()

dim dreader as sqlclient.sqldatareader = _

me.sqlcommand1.executereader()

while dreader.read()

dr = dtgenre.newrow()

dr(0) = dreader(0)

dtgenre.rows.add(dr)

end while

me.sqlconnection1.close()

else

dtgenre = ctype(application("genretable"), datatable)

end if

return dtgenre

end function

//c#

public datatable getgenretable()

{

datatable dtgenre = new datatable();

if(application["genretable"] == null)

{

datarow dr;

datacolumn dc = new datacolumn("genre");

dtgenre.columns.add(dc);

this.sqlconnection1.open();

system.data.sqlclient.sqldatareader dreader =

this.sqlcommand1.executereader();

while(dreader.read())

{

dr = dtgenre.newrow();

dr[0] = dreader[0];

dtgenre.rows.add(dr);

}

this.sqlconnection1.close();

}

else

{

dtgenre = (datatable) application["genretable"];

}

return dtgenre;

}

notice that the function caches the table it creates into application state. since the table is acting as a static lookup table, you do not need to re-read it every time a different row is put into edit mode. moreover, because the same table can be used by multiple users, you can cache it in the global application state rather than in user-specific session state.

the following shows the declaration for the template column. you will see that this is very similar to the syntax used for binding to a dataset table; the only real difference is that the datasource binding calls your function. a slight disadvantage of this technique is that you do not get much design-type assistance from visual studio. because you are defining the table to bind to in code, visual studio cannot offer you any choices for the datamember, datatextfield, and datavaluefield property settings. it is up to you to be sure that you set these properties to the names of the members you create in code.

<asp:templatecolumn headertext="genre (database)">

<itemtemplate>

<asp:label id=label1 runat="server"

text=<%# databinder.eval(container, "dataitem.genre") %>>

</asp:label>

</itemtemplate>

<edititemtemplate>

<asp:dropdownlist id=dropdownlist1 runat="server"

datasource="<%# getgenretable() %>"

datamember="genre"

datatextfield="genre"

datavaluefield="genre"

width="120px">

</asp:dropdownlist>

</edititemtemplate>

</asp:templatecolumn>

preselecting an item in the drop-down list

you often want to set the selected item in the drop-down list to match a specific value, usually the value displayed in the cell in display mode. you can do this by setting the selectedindex property of the drop-down list to the index of the value to display.

the following example shows a reliable way to do this in a handler for the datagrid items itemdatabound event. this is the correct event to use, because it guarantees that the drop-down list has already been populated, no matter what data source the drop-down list is using.

the trick is in knowing what value to set the drop-down list to. typically, the value is already available to you either in the current item (being displayed) or in the dataitem property of the current item, which returns a datarowview object containing the current record. once you have the value, you can use the dropdownlist controls findbytext or findbyvalue method to locate the correct item in the list; you can then use the items indexof property to return the index.

visual basic

private sub datagrid1_itemdatabound(byval sender as object, _

byval e as system.web.ui.webcontrols.datagriditemeventargs) _

handles datagrid1.itemdatabound

if e.item.itemtype = listitemtype.edititem then

dim drv as datarowview = ctype(e.item.dataitem, datarowview)

dim currentgenre as string = ctype(drv("genre"), string)

dim ddl as dropdownlist

ddl = ctype(e.item.findcontrol("dropdownlist1"), dropdownlist)

ddl.selectedindex = ddl.items.indexof(ddl.items.findbytext(currentgenre))

end if

end sub

// c#

private void datagrid1_itemdatabound(object sender,

system.web.ui.webcontrols.datagriditemeventargs e)

{

if(e.item.itemtype == listitemtype.edititem){

datarowview drv = (datarowview) e.item.dataitem;

string currentgenre = drv["genre"].tostring();

dropdownlist ddl =

(dropdownlist) e.item.findcontrol("dropdownlist1");

ddl.selectedindex =

ddl.items.indexof(ddl.items.findbytext(currentgenre));

}

}

selecting multiple items using a check box (hotmail model)

in applications such as microsoft hotmail&reg;, users can "select" rows by checking a box and then performing an operation on all the selected rows — for example, delete them or copy them.

to add functionality like this, add a template column to the grid and put a check box into the column. when the page runs, users will be able to check the items they want to work with.

to actually perform the user action, you can walk the grids items collection, looking into the appropriate column (cell) to see if the check box is checked. the following example shows how you can delete rows in a dataset corresponding to the items that a user has checked. the dataset, called dsbooks1, is assumed to contain a table called books.

visual basic

private sub btndelete_click(byval sender as system.object, _

byval e as system.eventargs) handles btndelete.click

walk the grid looking for selected rows

dim i as integer = 0

dim cb as checkbox

dim dgi as datagriditem

dim bookid as integer

dim dr as dsbooks.booksrow

for each dgi in datagrid1.items

cb = ctype(dgi.cells(0).controls(1), checkbox)

if cb.checked then

determine the key of the selected record …

bookid = ctype(datagrid1.datakeys(i), integer)

… get a pointer to the corresponding dataset record …

dr = me.dsbooks1.books.findbybookid(bookid)

… and delete it.

dr.delete()

end if

i += 1

next

me.sqldataadapter1.update(dsbooks1)

me.sqldataadapter1.fill(dsbooks1)

datagrid1.databind()

end sub

// c#

private void btndelete_click(object sender, system.eventargs e)

{

int i = 0;

checkbox cb;

int bookid;

dsbooks.booksrow dr;

foreach(datagriditem dgi in this.datagrid1.items)

{

cb = (checkbox) dgi.cells[0].controls[1];

if(cb.checked)

{

// determine the key of the selected record …

bookid = (int) datagrid1.datakeys[i];

// … get a pointer to the corresponding dataset record …

dr = this.dsbooks1.books.findbybookid(bookid);

// … and delete it.

dr.delete();

}

i++;

}

this.sqldataadapter1.update(this.dsbooks1);

this.sqldataadapter1.fill(this.dsbooks1);

datagrid1.databind();

}

some points to note:

you can determine whether the check box is checked by using the standard approach for getting a control value from a template column — getting an object from the controls collection of the cell and casting it appropriately. if you are getting a checkbox control, remember that it is usually the second control (index 1) because a literal control precedes it (even if it is blank).

if you are deleting, you must do so by key and not by offset in the dataset. the index of an item in the datagrid control might not match the index of the same record in the table. even if it does at first, after the first record is deleted it will not. here, the code gets the record key out of the grids datakey collection. it then uses the findby<key> method in the dataset table to locate the record to delete.

after the records have been deleted from the dataset (technically, they are only marked for deletion), you delete them from the database by calling the data adapters update method. the code then refreshes the dataset from the database and re-binds the grid.

editing multiple rows at once

the standard way to edit rows in the datagrid control — by adding an "edit, update, cancel" button to the grids columns — only allows users to edit one row at a time. if users want to edit multiple rows, they must click the edit button, make their changes, and then click the update button for each row.

in some cases, a useful alternative is to configure the grid so that it is in edit mode by default. in this scenario, the grid always displays editable data in text boxes or other controls; users do not explicitly have to put the grid into edit mode. typically, users make whatever changes they want and then click a button (not a button in the grid) to submit all changes at once. the page might look something like the following:

figure 1

you can use this style of editing grid with any data model, whether you are working against a dataset or directly against the data source using data commands.

to configure the grid for multiple-row edit, add the columns as you normally would and convert all editable columns to template columns. in the columns tab of the grids property builder, select the column and at the bottom of the window, choose convert this column into a template column. to edit the templates, right-click the grid and choose edit template.

add the edit controls to the itemtemplate. note that you are not adding them to the edititemtemplate, as you normally would, because the rows will not be displayed in edit mode. that is, the itemtemplate will contain editable controls.

set up data binding for the grid normally. you will need to bind each editable control individually. a typical data binding expression will look like this:

databinder.eval(container, "dataitem.title")

loading the grid is no different than usual. updating is slightly different, however, because when users click the update button, you need to go through the entire grid, making updates for all the rows.

the following example shows one possibility. in this case, it is assumed that you are using a data command (dcmdupdatebooks) that contains a parameterized sql update statement. the code walks through the grid, item by item, extracts values from the editable controls, and assigns the values to command parameters. it then executes the data command once for each grid item.

visual basic

private sub btnupdate_click(byval sender as system.object, _

byval e as system.eventargs) handles btnupdate.click

dim i as integer

dim dgi as datagriditem

dim bookid as integer

dim textboxtitle as textbox

dim checkboxinstock as checkbox

dim textboxprice as textbox

dim labelbookid as label

for i = 0 to datagrid1.items.count – 1

dgi = datagrid1.items(i)

labelbookid = ctype(dgi.cells(0).controls(1), label)

bookid = ctype(labelbookid.text, integer)

textboxtitle = ctype(dgi.findcontrol("textboxtitle"), textbox)

checkboxinstock = _

ctype(dgi.findcontrol("checkboxinstock"), checkbox)

textboxprice = ctype(dgi.findcontrol("textboxprice"), textbox)

me.dcmdupdatebooks.parameters("@bookid").value = bookid

me.dcmdupdatebooks.parameters("@title").value = textboxtitle.text

me.dcmdupdatebooks.parameters("@instock").value = _

checkboxinstock.checked

me.dcmdupdatebooks.parameters("@price").value = textboxprice.text

me.sqlconnection1.open()

me.dcmdupdatebooks.executenonquery()

me.sqlconnection1.close()

next

end sub

// c#

private void btnupdate_click(object sender, system.eventargs e)

{

int i;

datagriditem dgi;

int bookid;

textbox textboxtitle;

checkbox checkboxinstock;

textbox textboxprice;

for(i = 0; i <= datagrid1.items.count -1 ; i++)

{

dgi = datagrid1.items[i];

label labelbookid = (label) dgi.cells[0].controls[1];

bookid = int.parse(labelbookid.text);

textboxtitle = (textbox) dgi.findcontrol("textboxtitle");

checkboxinstock = (checkbox) dgi.findcontrol("checkboxinstock");

textboxprice = (textbox) dgi.findcontrol("textboxprice");

this.dcmdupdatebooks.parameters["@bookid"].value = bookid;

this.dcmdupdatebooks.parameters["@title"].value = textboxtitle.text;

this.dcmdupdatebooks.parameters["@instock"].value =

checkboxinstock.checked;

this.dcmdupdatebooks.parameters["@price"].value =

float.parse(textboxprice.text);

this.sqlconnection1.open();

this.dcmdupdatebooks.executenonquery();

this.sqlconnection1.close();

}

}

checking for changed items

one disadvantage of the update strategy illustrated above is that it can be inefficient to send updates to the dataset or database for each grid row if there have been only a few changes. if you are working with a dataset, you can add logic to check for changes between the controls in the grid and the corresponding columns in dataset rows. if you are not using a dataset — as in the example above — you cannot easily make this comparison, since it would involve a round trip to the database.

a strategy that works for both types of data sources is to establish a way to determine whether rows are "dirty" so you can check that before making an update. the definitive way to determine whether a row has been dirtied is to handle the changed event for the controls in a row. for example, if your grid row contains a textbox control, you can respond to the controls textchanged event. similarly, for check boxes, you can respond to a checkedchanged event.

in the handler for these events, you maintain a list of the rows to be updated. generally, the best strategy is to track the primary keys of the affected rows. for example, you can maintain an arraylist object that contains the primary keys of the rows to update.

imagine that you want to follow this strategy for the example above. create an instance of an arraylist object as a member of the page class:

visual basic

protected bookidlist as arraylist = new arraylist()

// c#

protected arraylist bookidlist = new arraylist();

then create a handler to add the book id to the arraylist object whenever a control is changed. the following code shows a handler that can be invoked when a textbox control raises its textchanged event or when a checkbox control raises its checkedchanged event:

visual basic

protected sub rowchanged(byval sender as object, _

byval e as system.eventargs)

dim dgi as datagriditem = _

ctype(ctype(sender, control).namingcontainer, datagriditem)

dim bookidlabel as label = ctype(dgi.cells(0).controls(1), label)

dim bookid as integer = ctype(bookidlabel.text, integer)

if not (bookidlist.contains(bookid)) then

bookidlist.add(bookid)

end if

end sub

// c#

protected void rowchanged( object sender, system.eventargs e)

{

datagriditem dgi = (datagriditem)(((control)sender).namingcontainer);

label bookidlabel = (label) dgi.cells[0].controls[1];

int bookid = int.parse(bookidlabel.text);

if (!bookidlist.contains(bookid))

{

bookidlist.add(bookid);

}

}

note the method cannot be private, or you will not be able to bind to it later.

it is helpful to understand that change events do not, by default, post the page back to the server. instead, the event is raised only when the page is posted some other way (usually via a click event). during page processing, the page and its controls are initialized, and then all change events are raised. only when the change events handlers have finished is the click event raised for the control that caused the post.

on to the rowchanged method illustrated above. the code needs to get the book id out of the current item. the event does not pass the item to you (as it does for many datagrid events, for example), so you have to work backwards. from the sender argument of the event, get the namingcontainer property, which will be the grid item. from there, you can drill back down to get the value of the label control that displays the book id.

you need to check that the book id is not already in the array. each control in the row raises the event individually, so if there has been a change in more than one control, you could potentially end up adding the book id to the array more than once.

the change events for controls are always raised and handled before click events. therefore, you can build the array list in the change event and know that it will be available when the event handler runs for the button click that posted the form (in this example, the btnupdate_click handler).

now that you have the array list, you can make a minor modification to the handler that manages the update. in the btnupdate_click, when you iterate through the data grid items, add a test to see if the current book id is in the array list; if so, make the update.

visual basic

private sub btnupdate_click(byval sender as system.object, _

byval e as system.eventargs) handles btnupdate.click

dim i as integer

dim dgi as datagriditem

rest of declarations here

for i = 0 to datagrid1.items.count – 1

dgi = datagrid1.items(i)

labelbookid = ctype(dgi.cells(0).controls(1), label)

if bookidlist.contains(bookid) then

textboxtitle = ctype(dgi.findcontrol("textboxtitle"), textbox)

rest of update code here

end if

next

end sub

// c#

private void btnupdate_click(object sender, system.eventargs e)

{

int i;

datagriditem dgi;

int bookid;

//rest of declarations here

for(i = 0; i <= datagrid1.items.count -1 ; i++)

{

dgi = datagrid1.items[i];

tablecell tc = dgi.cells[0];

string s = dgi.cells[0].text;

label labelbookid = (label) dgi.cells[0].controls[1];

bookid = int.parse(labelbookid.text);

if (bookidlist.contains(bookid))

{

// update code here

}

}

}

one task is left: binding the handlers to the control events. in visual studio, you can only do this in html view. the controls are not explicitly instantiated in the code-behind file, so they are not supported by the code tools. switch the .aspx file to html view and in the declarative elements for each of the controls, add the following highlighted syntax:

<asp:templatecolumn headertext="title">

<itemtemplate>

<asp:textbox ontextchanged="rowchanged"

id=textboxtitle runat="server"

text=<%# databinder.eval(container, "dataitem.title") %>>

</asp:textbox>

</itemtemplate>

</asp:templatecolumn>

<asp:templatecolumn headertext="instock">

<itemtemplate>

<asp:checkbox id=cbinstock oncheckedchanged="rowchanged"

runat="server"

checked=<%# databinder.eval(container, "dataitem.instock") %>>

</asp:checkbox>

</itemtemplate>

</asp:templatecolumn>

both the textbox and checkbox controls can call the same method from their respective change methods, because the signature for both event handlers is the same. that would be true also if you had a list box or drop-down list control, whose selectedindexchanged events likewise pass the same arguments.

selecting rows by clicking anywhere

the default model for selecting rows in the grid is for you to add a select button (actually, a linkbutton control) whose commandname property is set to "select." when the button is clicked, the datagrid control receives the select command and automatically displays the row in selected mode.

not everyone likes having an explicit select button, and a common question is how to implement the feature where users can click anywhere in a grid row to select it. the solution is to perform a kind of sleight-of-hand in the grid. you add the select linkbutton control as normal. users can still use it, or you can hide it. in either event, you then inject some client script into the page that effectively duplicates the functionality of the select button for the row as a whole.

the example below shows how. in the grids itemdatabound handler, first make sure that you are not in the header, footer, or pager. then get a reference to the select button, which in this instance is assumed to be the first control in the first cell. you then call a little-known method called getpostbackclienthyperlink. this method returns the name of the postback call for the designated control. in other words, if you pass in a reference to a linkbutton control, it returns the name of the client function call that will perform the postback.

finally, you assign the client-side method to the item itself. when the grid renders, it renders as an html table. by assigning the method to the item, it is the equivalent of adding client-side code to each row (<tr> element) in the table. the grids item object does not directly support a way to assign client code to it, but you can do that by using its attributes collection, which passes anything you assign to it through to the browser.

note one small disadvantage of this technique is that it adds somewhat to the stream rendered to the browser, and it adds information for each row to view state.

visual basic

private sub datagrid1_itemdatabound(byval sender as object, _

byval e as system.web.ui.webcontrols.datagriditemeventargs) _

handles datagrid1.itemdatabound

dim itemtype as listitemtype = e.item.itemtype

if ((itemtype = listitemtype.pager) or _

(itemtype = listitemtype.header) or _

(itemtype = listitemtype.footer)) then

return

else

dim button as linkbutton = _

ctype(e.item.cells(0).controls(0), linkbutton)

e.item.attributes("onclick") = _

page.getpostbackclienthyperlink(button, "")

end if

end sub

// c#

private void datagrid1_itemdatabound(object sender,

system.web.ui.webcontrols.datagriditemeventargs e)

{

listitemtype itemtype = e.item.itemtype;

if ((itemtype == listitemtype.pager) ||

(itemtype == listitemtype.header) ||

(itemtype == listitemtype.footer))

{

return;

}

linkbutton button = (linkbutton)e.item.cells[0].controls[0];

e.item.attributes["onclick"] =

page.getpostbackclienthyperlink(button, "");

}

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » DataGrid常见关注问题解决方案-.NET教程,数据库应用
分享到: 更多 (0)