retrieve data key of selected row in gridview in asp.net - asp.net

I have a button (item template) in any rows of a gridView.
I want when user clicks on this button, I retrieve dataKey of row that there is that button in it.
how can I do this?
(sorry,I can't speak and write English very well)

Assuming you have one DataKey and it is an int and the row of the button isn't necessarily selected and you have connected the following function to the buttons in your template field:
protected void RowClicked(object sender, EventArgs e)
{
Button TempButton = sender as Button;
if (TempButton != null)
{
GridViewRow GVR = TempButton.Parent.Parent as GridViewRow;
if (GVR != null)
{
int ID = (int) GridView1.DataKeys[GVR.DataItemIndex].Value;
}
}
}

Try the SelectedIndexChanged event. Something like this:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e){
TextBox1.Text = GridView1.SelectedRow.Cells[1].Text;
TextBox2.Text = GridView1.SelectedRow.Cells[2].Text;
.
.
.
}

Related

Dynamic template field in grdivew post back values

//Bedlow is the page_load code to add dynamic controls in page load. and load of page_load
gvSecond 's dynamic template fields will be added.I want to know why the dot is appended on each postback values
protected void Page_Load(object sender, EventArgs e)
{
gvFirst.DataSource = GetData("select top 10 * from Project_Master");
gvFirst.DataBind();
}
//gvFirst has gvSecond and on rowdatabound of the gvFirst gvSecond populated with dynamic template fields. and all the template fields has the TextBoxtes in it
protected void gvFirst_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
//below code to generate dynamic template column
gvFirst.DataSource = GetData("select top 10 * from Project_Master");
gvFirst.DataBind();
//Added dynamic controls in gvSecond
protected void gvFirst_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string customerId = gvFirst.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvSecond = e.Row.FindControl("gvSecond") as GridView;
DataTable dt= GetData1(Convert.ToInt32(customerId));
foreach (DataColumn col in dt.Columns)
{
//Declare the bound field and allocate memory for the bound field.
TemplateField bfield = new TemplateField();
//Initalize the DataField value.
bfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);
//Initialize the HeaderText field value.
bfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName);
//Add the newly created bound field to the GridView.
gvSecond.Columns.Add(bfield);
}
TotalColumns = dt.Columns.Count;
gvSecond.DataSource = dt;
gvSecond.DataBind();
}
}
}
//This is used to add the dynamic template in gvSecond.Now when I click on button textbox values appended with postback values and older values seperated by dot(.)
You need to wrap the code in Page_Load in if(!IsPostback){}:
EDIT :
Edited to create second grid at postback.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
gvFirst.DataSource = GetData("select top 10 * from Project_Master");
gvFirst.DataBind();
}
else
{
CreateSecondGridView();
}
}
And your Rowdatabound may look like this:
protected void gvFirst_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
CreateSecondGridView();
}
protected void CreateSecondGridView()
{
foreach(GridViewRow row in gvFirst.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
string customerId = gvFirst.DataKeys[row.RowIndex].Value.ToString();
GridView gvSecond = row.FindControl("gvSecond") as GridView;
DataTable dt= GetData1(Convert.ToInt32(customerId));
foreach (DataColumn col in dt.Columns)
{
//Declare the bound field and allocate memory for the bound field.
TemplateField bfield = new TemplateField();
//Initalize the DataField value.
bfield.HeaderTemplate = new GridViewTemplate(ListItemType.Header, col.ColumnName);
//Initialize the HeaderText field value.
bfield.ItemTemplate = new GridViewTemplate(ListItemType.Item, col.ColumnName);
//Add the newly created bound field to the GridView.
gvSecond.Columns.Add(bfield);
}
TotalColumns = dt.Columns.Count;
gvSecond.DataSource = dt;
gvSecond.DataBind();
}
}
}

How to remove row from gridview on row command event?

I am trying to remove row from gridview by click on ImageButton which is placed inside gridview. I am getting row index but dont know how to remove. My gridview binds from session and i dont want to rebind gridview.
Here is my code:
protected void GVDetail_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Remove"))
{
List<Class1> list = (List<Class1>)Session["value1"];
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gridRow = gvDetail.Rows[index];// (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
((List<Class1>)Session["value1"]).RemoveAt(index);
}
}
If anyone have any idea about this than please help me..
Use the gridview deleterow method.
void GVDetail_RowCommand_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Remove")
{
var id = Int32.Parse(e.CommandArgument);
GVDetail.DeleteRow(id);
}
}
protected void GVPurchaseOrderTax_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
if (dt.Rows.Count > 0)
{
dt.Rows[e.RowIndex].Delete();
GVPurchaseOrderTax.DataSource = dt;
GVPurchaseOrderTax.DataBind();
}
}
}

How to get the value of selected row using radiobutton in gridview in a button click

i need to get the value of the selected row of radiobutton in the gridview. the selected value is assigned to a textbox. my code is
protected void lnBTNDone_Click(object sender, EventArgs e)
{
GridViewRow gvRow = grdEventDetails.SelectedRow;
txtEventId.Text = gvRow.Cells[0].Text;
}
the problem is the gvRow value is assigned as null .
the linkbutton is not inside gridview. the gridview n linkbutton and the textbox are inside the user controls.
You can always get the GridViewRow via the sender's NamingContainer:
protected void lnBTNDone_Click(object sender, EventArgs e)
{
LinkButton lnBTNDone = (LinkButton)sender;
GridViewRow row = (GridViewRow)lnBTNDone.NamingContainer;
txtEventId.Text = row.Cells[0].Text;
}
Assuming that the LinkButton is in the selected row.
Btw, i'm yet not sure why SelectedRow is null there, maybe because the GridView's SelectedIndexChanged event is triggered after the LinkButton's click event.
protected void lnBTNDone_Click(object sender, EventArgs e)
{
for (int i = 0; i < grdEventDetails.Rows.Count; i++)
{
RadioButton rb = (grdEventDetails.Rows[i].FindControl("grdRdo")) as RadioButton;
if (rb.Checked == true)
{
txtEventId.Text = grdEventDetails.Rows[i].Cells[1].Text;
}
}
}

How do i know id of ListView item on OnItemUpdated?

I have suppliers table with id int value for each supplier. I'm trying to edit columns of this table inside of ListView.
i'm trying to access e arg but it doesn't have any data on id of the row i'm trying to update?
You need to set the ListView.DataKeyNames to contain the property name of the uniqueId
<asp:ListView runat="server" ID="LvSample" DataKeyNames="SupplierId"/>
Then the dataKey will be available in the update events. It is worth nothing that you might want to use the ItemUpdating event instead of the ItemUpdated as this happens before Update occurs.
protected void Page_Load(object sender, EventArgs e)
{
LvSample.ItemUpdating += new EventHandler<ListViewUpdateEventArgs>(LvSample_ItemUpdating);
LvSample.ItemUpdated += new EventHandler<ListViewUpdatedEventArgs>(LvSample_ItemUpdated);
}
void LvSample_ItemUpdated(object sender, ListViewUpdatedEventArgs e)
{
var supplierId = e.NewValues["SupplierId"];
}
void LvSample_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
var supplierId = e.Keys["SupplierId"];
}
use the sender instead of the e
protected void ListView1_ItemUpdated(object sender, ListViewUpdatedEventArgs e)
{
if ((sender as ListView) != null)
{
ListView l = (ListView)sender;
l.SelectedIndex;
l.etc..............
DataKey key = l.SelectedDataKey;
object k = key.Values["foo"];
}
}

asp.net making a gridView column invisible

This is a Master-Detail form. Master is a GridView. And, the Detail is a DetailsView.
The entire thing is achieved programmatically.
As you can see from the code, DetailsView is using the Master-objects's ID to retrieve the Detail items.
I need to make the ID column of the Master-GridView invisible. Coz, it is irrelevent for the user of the page. But it must not harm the page logic.
But the code-line, GridView1.Columns[1].Visible = false; is generating an exception.
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
How should I solve this problem?
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
List<Order> orders = Order.Get();
GridView1.DataSource = orders;
GridView1.DataBind();
// This is giving Error...............!!!
GridView1.Columns[1].Visible = false;
// At first, when the page first loads,
// GridView1.SelectedIndex == -1
// So, this is done to automatically select the 1st item.
if (GridView1.SelectedIndex < 0)
{
GridView1.SelectedIndex = 0;
}
int selRowIndex = GridView1.SelectedIndex;
int selMasterId = Convert.ToInt32(GridView1.Rows[selRowIndex].Cells[1].Text);
Order master = Order.Get(selMasterId);
labItemsCount.Text = master.Items.Count.ToString();
DetailsView1.DataSource = master.Items;
DetailsView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
BindData();
}
protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
{
DetailsView1.PageIndex = e.NewPageIndex;
BindData();
}
}
Have you considered using the DataKeyNames property of the gridview? This way you can remove the 'id' column from the GridView bu still access the 'id' value in the Page_Load.
DataKeyNames = "id"
Then you can get the value of the id like this.
int selRowIndex = GridView1.SelectedIndex;
int selMasterId = Convert.ToInt32(GridView.DataKeys[selRowIndex].Value);
Order master = Order.Get(selMasterId);
Alternately, you could try changing the visibility of the column in the OnRowBound event of the GridView.
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header ||
e.Row.RowType == DataControlRowType.DataRow ||
e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[1].Visible = false;
}
}

Resources