Dynamically add row to GridView / DataGrid / Repeater?

二次信任 提交于 2020-01-15 11:39:56

问题


I want to create a "table" that the user will complete which has an unknown number of rows.

To illustrate it, let's say it is to enter details from a receipt after a shopping trip - i.e. the number of rows (or items) will be unknown.

To acheive this I want to create a grid with a single row, and two columns containing textboxes to enter the item name and price:

+-------+---------+
+ Item + Price +
+-------+---------+
+ Beans + 0.99 +
+-------+---------+

Then after the first row has been completed I want to generate another row on the fly and so on.

Which is the best control for this? Am fairly new to asp.net so not sure if I should be using a Gridview / DataGrid / Repeater or what. (Not sure if it has any relevance, but the item texbox has an Ajax AutoCompleteExtender associated.)

Any pointers would be most welcome.

EDIT

One thing I forgot to mention is that the GridView (or whatever) has no data bound to it when it is loaded. Not sure if that impacts the decision.


回答1:


GridViews aren't really good at adding rows inline. You'll probably have to do something a little hacky. You might be able to set up the data source on your grid view so that there is always one more empty row at the end of your real data, and then just make sure that you set the last row in the grid to be in edit mode every time the gridview finishes binding. Then you'd have to intercept the Update action and make it actually Insert instead of updating. Then there's the question of whether you also want to allow the user to edit existing rows: when editing an existing row you'd need to eliminate the "empty" row because you can't have two editable rows at the same time. It's tricky, but you could probably do it.

The alternative would be to use a repeater to show all your existing rows in read-only mode, and then just output an editable row at the end.

I'm not sure which I'd choose at this point.




回答2:


you surely can use a repeater but if you identify the structure of the data as a grid ( meaning that you plan or may plan to add new columns in the future for example ), a GridView is probably the best.



来源:https://stackoverflow.com/questions/4901120/dynamically-add-row-to-gridview-datagrid-repeater

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!