PDA

View Full Version : مبتدی: خواندن مقدار یک فیلد در gridview



hattarzadeh
یک شنبه 28 خرداد 1391, 12:03 عصر
باسلام
من یه gridview دارم که شامل یه سری سطر و ستونه می خوام این امکان رو داشته باشه که کاربر بتونه بر روی یکی از این فیلدها کلیک کنه و من تو برنامم بعد از اینکه کلید مثلا حذف رو زد بتونم مقدار فیلدی که انتخاب شده رو بخونم.
ممنون از راهنماییهاتون

alonemm
یک شنبه 28 خرداد 1391, 13:29 عصر
باسلام

به کد زیر دقت کنید:

ساخت یک گرید ویو و یک دیتا سورس. توجه داشته باشید برای فعال شدن دکمه انتخاب برای هر سطر خصوصیت autogenerateselectbutton شی GridView رو برابر با True قرار بدید.

<h3>GridViewRow Example</h3>

<asp:label id="Message"
forecolor="Red"
runat="server"/>

<br/>

<asp:gridview id="AuthorsGridView"
datasourceid="AuthorsSqlDataSource"
autogeneratecolumns="false"
autogenerateselectbutton="true"
onselectedindexchanged="AuthorsGridView_SelectedIndexChanged"
runat="server">

<columns>
<asp:boundfield datafield="au_lname"
headertext="Last Name"/>
<asp:templatefield headertext="FirstName">
<itemtemplate>
<%#Eval("au_fname")%>
</itemtemplate>
</asp:templatefield>
</columns>

</asp:gridview>

<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Pubs sample database. -->
<asp:sqldatasource id="AuthorsSqlDataSource"
selectcommand="SELECT [au_lname], [au_fname], [address], [city], [state], [zip], [contract] FROM [authors]"
connectionstring="server=localhost;database=pubs;integrated security=SSPI"
runat="server">
</asp:sqldatasource>


برای دستیابی به سلول های ردیف انتخاب شده از شی GridView هم همانند زیر عمل کنید:

void AuthorsGridView_SelectedIndexChanged(Object sender, EventArgs e)
{

// Get the selected row from the GridView control.
GridViewRow selectRow = AuthorsGridView.SelectedRow;

// Get the author's first and last name from the appropriate
// cells in the selected row. For BoundField field columns
// and automatically generated field columns, the Text property
// of a cell is used to access a field value.
String lastName = selectRow.Cells[1].Text;

// In a TemplateField column where a data-binding expression
// is used directly in the ItemTemplate, the field value
// is automatically placed in DataBoundLiteral control.

// Retrieve the DataBoundLiteral control from the cell. The
// DataBoundLiteral control is the first control in the
// Controls collection.
DataBoundLiteralControl firstNameLiteral = (DataBoundLiteralControl)selectRow.Cells[2].Controls[0];
String firstName = firstNameLiteral.Text;

// Display the name of the selected author.
Message.Text = "You selected " + firstName + " " + lastName + ".";

}




موفق باشید.