How to find control on GridView RowCommand Event? - asp.net

i tried something like this but did not work:
GridViewRow row = (GridViewRow)(((Repeater)e.CommandSource).NamingContainer);
Repeater _rpt1 = row.Cells[8].FindControl("rptReg") as Repeater;
error:
Unable to cast object of type 'System.Web.UI.WebControls.Button' to type 'System.Web.UI.WebControls.Repeater'.
is there a way i can have the below code in OnRowCommand event using GridView?
actually i am trying to delete the row from the gridview control and when the user click on it and i am grabbing the mulitple ids and passing to SP and update the table and databind the gridview
GridViewRow row = gv.SelectedRow;
Repeater _rpt = gv.Rows[e.RowIndex].Cells[8].FindControl("rptReg") as Repeater;
Repeater _rpt1 = gv.Rows[e.RowIndex].Cells[9].FindControl("rptVisitor") as Repeater;
foreach (RepeaterItem item in _rpt.Items)
{
TextBox _txt = item.FindControl("txtId") as TextBox;
TextBox _txt1 = item.FindControl("txtName") as TextBox;
//update db
}

Please try this:
var viewRow = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
foreach (GridViewRow gvr in gvDetails.Rows)
{
var btnSelect = (ImageButton)viewRow.FindControl("btnSelect");
if (gvr == viewRow)
{
if (btnSelect.ImageUrl.ToLower() == "~/images/rbnormal.jpg")
{
btnSelect.ImageUrl = "~/Images/rbSelected.jpg";
btnSelect.Enabled = false;
}
}
else
{
btnSelect.ImageUrl = "~/Images/rbnormal.jpg";
btnSelect.Enabled = true;
}
}

Your error is telling me that the control named "rptReg" is a button.
The GridView has a property called DataKeys which can hold multiple IDs
So you would pull out the "PersonId" like:
string personId = GridView1.DataKeys[e.RowIndex]["PersonId"].ToString();

Related

Rows added to gridview don't persist when save event is triggered

I have a gridview on my webpage that can have rows added dynamically. There is a for loop that adds the rows like this:
protected void AddNewJob(object sender, EventArgs e)
{
for(int i = 0; i < Convert.ToInt32(newJobCount.Text);i++)
{
TableRow tr = new TableRow();
tr.Cells.Add(ServicesDDL("-- Select Service Type --"));
tr.Cells.Add(JobsDDL("-- Select Job Type --"));
tr.Cells.Add(TextBoxCell());
tr.Cells.Add(TextBoxCell());
tr.Cells.Add(TextBoxCell());
assetTable.Rows.Add(tr);
}
}
After the rows are added and changed from their default values the rows are looped through and data is saved to the database. I'm having problems getting the rows added to the gridview to persist and exist on the gridview when the page's save event is triggered. That code looks like this:
foreach (TableRow row in assetTable.Rows)
{
if (isFirst)
{
isFirst = false;
continue;
}
DropDownList service = (DropDownList)row.Cells[0].Controls[0];
string assetText = service.SelectedItem.Value;
DropDownList jobDescription = (DropDownList)row.Cells[1].Controls[0];
string serialText = jobDescription.SelectedItem.Value;
TextBox equipmentCount = (TextBox)row.Cells[2].Controls[0];
string leaseText = equipmentCount.Text;
TextBox jobSize = (TextBox)row.Cells[3].Controls[0];
string originText = jobSize.Text;
TextBox serialNo = (TextBox)row.Cells[4].Controls[0];
string deliveryText = serialNo.Text;
string oNo = orderNo.Text;
if (assetText != "0" && serialText != "0")
{
APICallClass.Job j = new APICallClass.Job();
j.JobTypeID = Convert.ToInt32(serialText);
j.serviceID = Convert.ToInt32(assetText);
j.equipment = leaseText;
j.jobSize = originText;
j.serialNumbers = deliveryText;
j.orderID = Convert.ToInt32(global.GlobalID);
APICallClass.API.AddJob(j, Session["Variable"].ToString());
}
}
When the code pasted above runs, it only sees the rows that are pulled in from the database. I think my problem could be fixed by calling something like .databind() somewhere that I'm not, but I've tried a few places and they have not fixed the problem.
Thanks in advance for any help, and helping me become a more robust ASP.NET developer.
When a GridView is DataBind()-ed, the contents of the GridView are "rebuilt" based on the the GridView's DataSource. If you need the new row to stay in the GridView, either do not call DataBind() after the new row is added, or ensure that the contents of your new row are in the GridView's DataSource before future calls to DataBind().
In a page I wrote once I had a similar situation and did the latter. The data for the initial rows was pulled from the database on the first page load and persisted in ViewState. As the user added, removed, and reordered rows in the GridView, the page just changed the data in ViewState and re-DataBind()ed the GridView.

get gridview data of each cell of each row as variables from a webusercontrol to webform in asp.net

I need to get gridview values of each cell of each row as variables which are displayed using webusercontrol on a webform in asp.net
i tried this but it isn't working,
Control control1 = null;
GridView GridView1 = (GridView)this.FindControl("GridView");
foreach (GridViewRow row1 in GridView1.Rows)
{
control1 = GridView1.Controls[0].Controls[0];
string Price = (control1.FindControl("Price") as Label).Text;
string Quantity = (control1.FindControl("Quantity") as Label).Text;
}
You are already looping all GridViewRows, these are the controls which are the NamingContainers of your labels in the ItemTemplate which you can find with row.FindControl:
foreach (GridViewRow row in GridView1.Rows)
{
Label lblPrice = (Label)row.FindControl("Price");
string Price = lblPrice.Text;
Label lblQuantity = (Label)row.FindControl("Quantity");
string Quantity = lblQuantity.Text;
}

how to pass grid data in a gridview template textbox

I have a grid view name gvwsponsoor and it has 8 cells every cells has template textbox. if i am double click this textbox then open a model popup. i selected this popup data the data is show the textbox. but second rows are not show data, always data show first rows, how to pass all rows show data, please tell me solution any person .
i try to solved this code but not work in this code.
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//foreach (GridViewRow grid in gvwSponsor.Rows)
//{
TextBox CostId = (TextBox)gvwSponsor.Rows[0].Cells[2].FindControl("txtCostCenter");
TextBox CostName = (TextBox)gvwSponsor.Rows[0].Cells[1].FindControl("txtDescription");
CostId = (TextBox)gvwSponsor.Rows[0].Cells[2].FindControl("txtCostCenter");
CostName = (TextBox)gvwSponsor.Rows[0].Cells[1].FindControl("txtDescription");
CostId.Text = GridView1.SelectedRow.Cells[2].Text;
CostName.Text = GridView1.SelectedRow.Cells[1].Text;
GridView1.SelectedIndex = -1;
DataTable dtaa = new DataTable();
dtaa = bll.GetNumber(CostId.Text);
if (dtaa.Rows.Count > 0)
{
GridView2.DataSource = dtaa;
GridView2.DataBind();
}
TextBox TxtOp = (TextBox)gvwSponsor.Rows[0].FindControl("txtOP");
TxtOp.Focus();
//}
}
You should process SelectedIndexChanged function of your gridview by using gvwSponsor.SelectedRow, not gvwSponsor.Rows[0]

Datalist Controls access in ASP.NET

i am using a DataList that contains a few TextBox within a table. i had tried the code is the code behind
TextBox txtbox = dlCRR.FindControl("TextBox1") as TextBox;
The error is
Object reference not set to an instance of an object.
When i debug i am seeing a null value. why is this?
You won't be able to find the textbox directly from the datalist control. You will have to find it from the DataList.Items.
Ex:
TextBox txt = myDataList.Items[indexOfWhatIamLookingFor].FindControl("TextBox1") as TextBox;
or if you want to iterate all items
foreach (DataListItem dli in myDataList.Items)
{
TextBox txt = dli.FindControl("TextBox1") as TextBox;
}

Setting selected value to DropDownList in UserControl

Could someone help me with setting the selected value of the DropDownList to the database given value. I have couple of TextBoxes for which it isn't hard to set the value from the database, but what drives me crazy is DropDownList.
<asp:TextBox ID="txtNaziv" runat="server" Width="430px" Text='<%# DataBinder.Eval(Container, "DataItem.Naziv") %>'></asp:TextBox>
As far as I know, it isn't possible to set the selected item value from the code front to the DropDownList, but I was able to find out something like this (code snippet from Telerik's RadGrid documentation):
protected void EmployeeDetails_DataBinding(object sender, System.EventArgs e)
{
ArrayList tocs = new ArrayList(new string[] { "Dr.", "Mr.", "Mrs.", "Ms." });
ddlTOC.DataSource = tocs;
ddlTOC.DataBind();
object tocValue = DataBinder.Eval(DataItem, "TitleOfCourtesy");
if (tocValue == DBNull.Value)
{
tocValue = "Mrs.";
}
ddlTOC.SelectedIndex = tocs.IndexOf((string)tocValue);
ddlTOC.DataSource = null;
}
The problem is I'm using Linq-to-SQL and I'm not sure how to recreate something like the above code. This is what I currently have:
protected void ddlTip_DataBinding(object sender, EventArgs e)
{
TSEntities db = new TSEntities();
var partType = (from pt in db.PartType
select new { pt.idPartType, pt.Naziv }).ToArray();
ddlTip.DataSource = partType;
ddlTip.DataTextField = "Naziv";
ddlTip.DataValueField = "idPartType";
ddlTip.DataBind();
object Tip = DataBinder.Eval(DataItem, "idPartType");
}
One more thing I have to add that this TextBoxes and DropDownList are inside the UserControl which is being used inside Telerik's RadGrid for its EditForm.
Any help would be appreciated.
Thank you!
You need to set the SelectedValue of the dropdown:
ddlTOC.SelectedValue = tocValue;
You can also do it like this:
ListItem li = ddlTOC.Items.FindByValue(tocValue);
if (li != null)
li.Selected = true;
EDIT:
Included code to bind list directly to db.PartType:
TSEntities db = new TSEntities();
ddlTip.DataSource = db.PartType;
ddlTip.DataTextField = "Naziv";
ddlTip.DataValueField = "idPartType";
ddlTip.DataBind();
ddlTip.SelectedValue = DataBinder.Eval(DataItem, "idPartType").ToString();
Try this one
ddlTip.Items.FindByValue(tocs).Selected = true;

Resources