通常觸發Button_Click後需要傳遞GridView中一些資料作為輸入的資料來源,
之前筆者是使用如下面程式碼的方式抓取GridView中的Label或TextBox的文字以便輸入資料:
--為方便比較筆者將Button的屬性一並放上
--aspx檔部分
<asp:Button ID="Button1" runat="server" CommandName="ShopCar" Text="Button" />
--cs檔部分
Label booksid = (Label)DataList1.Items[e.Item.ItemIndex].FindControl("booksidLabel");
Label booksname = (Label)DataList1.Items[e.Item.ItemIndex].FindControl("booksnameLabel");
Label booksprice = (Label)DataList1.Items[e.Item.ItemIndex].FindControl("bookspriceLabel");
這種作法最大的缺點每抓取一筆資料就需要宣告一個Label或TextBox物件
程式無法撰寫的太精簡,因為需要這些屬性。
後來筆者參考這個網址的做法:以CommandArgument傳遞多個參數
將程式碼改為CommandArgument傳遞所需的參數,如此一來不需要知道Label的ID也能傳遞參數。
--aspx檔部分
<asp:Button ID="Button1" runat="server" CommandName="ShopCar" Text="Button"
CommandArgument='<%# Eval("booksid")+","+ Eval("booksname")+","+Eval("booksprice") %>' />
--cs檔部分則改為
string booksid = e.CommandArgument.ToString().Split(',')[0].Trim();string booksname = e.CommandArgument.ToString().Split(',')[1].Trim() ;
string booksprice = e.CommandArgument.ToString().Split(',')[2].Trim();
以這個程式碼為例,筆者要傳遞三個參數,筆者不需要知道三個Label的ID就能直接抓取與booksid booksname booksprice繫結的欄位並將資料傳遞至cs檔中暫存。
對於常常搞混Label ID的筆者而言的確比較方便,也不會因為更動GridView繫結的物件造成資料錯誤。
沒有留言:
張貼留言