I am binding data in Gridview control in page load event.
How to get a selected column's data in a string from the Gridview control?
(ie)It is the primary key of that table,so for every row selected by user there will be a primary key ID column bounded to it. So I need to get that ID & with this ID, I need to link with the next page of my web application.
Using Visual Studio 2005 asp.net C# 2.0.
Below is some of the code what I tried :
protected void SubmitButton_Click(object sender, EventArgs e)
{
string bS = Convert.ToString(gridview1.Rows[rowIndex].Cells[2].Text);
}
Do something like this:
EDIT
Add a hidden field to your markup:
<asp:HiddenField ID="hdnID" runat="server" />
<asp:GridView ID="GridView1" runat="server"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
... ... ... ... ... ... ... ... ... ... ... ...
On GridVew's selectedIndexChanged event, set the vallue to hidden field:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
hdnID.Value = row.Cells[2].Text;
}
In button event get the value from hidden field:
protected void SubmitButton_Click(object sender, EventArgs e)
{
string bS = hdnID.Value;
}
You can use RowCommand
event. Below is a sample from my code. You should use DataKey
s to provide a button field in GridView
and give CommandName = Select
.
protected void GridView_AccGroups_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select") //commandName given to the button field in the Gridview
{
foreach (GridViewRow i in GridView_AccGroups.Rows) //takes each Gridview Row..my Gridview name is 'GridView_AccGroups'
{
try
{
int index = Convert.ToInt32(e.CommandArgument); // gets the selected Index
GridViewRow selectedRow = GridView_AccGroups.Rows[index]; // with the selected index gets the selected Row
string txtAccGroupName = GridView_AccGroups.DataKeys[index].Values["Account Group"].ToString(); // DataKey Names are given in the Gridview Properties..!! each key name in one line,these key names are column names in the result of the select query that is bound to the Gridview,
string txtAccGroupShortName = GridView_AccGroups.DataKeys[index].Values["Short Name"].ToString();
string txtAccGroupRemarks = GridView_AccGroups.DataKeys[index].Values["Remarks"].ToString();
string id = GridView_AccGroups.DataKeys[index].Values["ID"].ToString();
string = GridView_AccGroups.DataKeys[index].Values["Parent Group ID"].ToString();
}
catch (Exception ex)
{
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.