星期三, 5月 14, 2008

在gridview的edit模式下動態動態塞入值

很多時候都用的到..例如常常都會要編輯的時候..才會知道gridview編輯模式裡的值..例如validation..droplist等等..所以我就簡單的寫了這個gridview+droplist的範例..裡面的事件方法也常用到..參考一下ㄅ..

123

aspx

<form id="form1" runat="server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString %>"
SelectCommand="SELECT [EmployeeID], [LastName], [FirstName], [Title] FROM [Employees]">
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID"
DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="EmployeeID" InsertVisible="False" SortExpression="EmployeeID">
<EditItemTemplate>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString %>"
SelectCommand="SELECT [OrderID], [ShipName] FROM [Orders] WHERE ([EmployeeID] = @EmployeeID)">
<SelectParameters>
<asp:Parameter Name="EmployeeID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2"
DataTextField="ShipName" DataValueField="OrderID">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("EmployeeID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="LastName" HeaderText="LastName" ReadOnly="True" SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" ReadOnly="True" SortExpression="FirstName" />
<asp:BoundField DataField="Title" HeaderText="Title" ReadOnly="True" SortExpression="Title" />
<asp:TemplateField>
<EditItemTemplate>
update
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>

cs

public partial class test_dataSource : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//只對datarows作用
if (e.Row.RowType == DataControlRowType.DataRow)
{
//判斷是否是編輯欄..因為gridview還有分單雙所以要多加Alternamte
if (e.Row.RowState == DataControlRowState.Edit ||
e.Row.RowState == (DataControlRowState.Edit | DataControlRowState.Alternate))
{
//把sqldatasource餵值
string id = GridView1.DataKeys[e.Row.RowIndex][0].ToString();
((SqlDataSource)e.Row.FindControl("SqlDataSource2")).
SelectParameters["EmployeeID"].DefaultValue = id;
}
}
}
}

重點就是..那偶數跟單數的判斷方式..因為有時忘了..程式寫出來..真的會ox..^^..

參考:

3 則留言:

曉羽 提到...

找了好久在gridview中edit的findcontrol方法,試了好幾個方式都無效,終於找到你的網頁,解決我的難題。

匿名 提到...

請問用VB要怎樣寫呢?!

Bibby 提到...

你到這網站吧
http://www.developerfusion.com/tools/convert/csharp-to-vb/

這也許可以幫你..vb我不是很熟..^^..
有問題再提出來吧..