2012-11-29 42 views
0

有人可以發佈一個GridView的工作示例,所有行可編輯(如它是一個Excel)和list<type>作爲數據源?ASP.net所有行可編輯GridView與列表<type>作爲數據源

我們想要保留用戶在回髮網格中輸入的數據(這可能是由任何控件生成的,不僅僅是提交的數據),然後從列表或網格視圖獲取數據,因此我們使用它來插入或更新不同的表格(這不是1:1關係/ grid:sqltable的典型案例)

此外,我們還有一個下拉列表(帶有autopostback),其編號爲1到9,用於控制在gridview中使用多少行,如果用戶從1行更改爲5行,則將在gridview中添加4個新行,並且如果他從8行更改爲5行,則最後3行將被刪除...(調用當前由用戶輸入的數據)

謝謝正手

回答

0

解決這樣的: ASPX:

<asp:DropDownList ID="ddlNItems" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlNItems_SelectedIndexChanged"> 
    <asp:ListItem Selected="True">1</asp:ListItem> 
    <asp:ListItem>2</asp:ListItem> 
    <asp:ListItem>3</asp:ListItem> 
    <asp:ListItem>4</asp:ListItem> 
    <asp:ListItem>5</asp:ListItem> 
    <asp:ListItem>6</asp:ListItem> 
    <asp:ListItem>7</asp:ListItem> 
    <asp:ListItem>8</asp:ListItem> 
    <asp:ListItem>9</asp:ListItem> 
</asp:DropDownList> 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="True"> 
    <Columns> 
     <asp:TemplateField HeaderText="Código"> 
      <ItemTemplate> 
       <asp:TextBox ID="txtCodMuestra" runat="server" Text='<%# Eval("cod") %>' /></ItemTemplate> 
      </asp:TemplateField> 
      <asp:TemplateField HeaderText="Tipo"> 
       <ItemTemplate> 
        <asp:DropDownList runat="server" ID="ddlTipo" SelectedValue='<%# Eval("Tipo") %>'> 
         <asp:ListItem Value="a">A</asp:ListItem> 
         <asp:ListItem Value="b">B</asp:ListItem> 
         <asp:ListItem Value="c">C</asp:ListItem> 
        </asp:DropDownList> 
       </ItemTemplate> 
      </asp:TemplateField> 
     </Columns> 
    </asp:GridView> 

CS:

public class Itemx 
{ 
    public string cod { get; set; } 
    public string Tipo { get; set; } 
} 
public static List<Itemx> LItems 
{ 
    get 
    { 
     return (List<Itemx>)Session["LItems"]; 
    } 
    set 
    { 
     Session["LItems"]= value; 
    } 
} 
void InitializeItems() 
{ 
    LItems = new List<Itemx>(); 
    ConfigItems(); 
} 
void ConfigItems() 
{ 
    int numitems = Convert.ToInt32(ddlNItems.SelectedValue); 


    if (LItems.Count > numitems) 
    { 
     for (int i = GridView1.Rows.Count; i > numitems; i--) 
     { 
      LItems.RemoveAt(i - 1); 
     } 
    } 
    else if (LItems.Count < numitems) 
    { 
     for (int i = GridView1.Rows.Count; i < numitems; i++) 
     { 
      LItems.Add(new Itemx { Tipo = "a" }); 
     } 
    } 
    transferGridtoList(); 

    GridView1.DataSource = LItems; 
    GridView1.DataBind(); 

    GridView1.HeaderRow.TableSection = TableRowSection.TableHeader; 
} 
private void transferGridtoList() 
{ 
    for (int i = 0; i < LItems.Count && i < GridView1.Rows.Count; i++) 
    { 
     LItems[i].cod = ((TextBox)GridView1.Rows[i].Cells[0].Controls[1]).Text; 
     LItems[i].Tipo = ((DropDownList)GridView1.Rows[i].Cells[1].Controls[1]).SelectedValue; 
    } 
} 

protected void ddlNItems_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    ConfigItems(); 
}