Finding controls in gridview? In Asp.net? - asp.net

In web applicatiom i am trying to find grid controls in RowDataBound event. But it is giving object reference to instance of an object, this is my code :
protected void mygrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
string empid = "";
empid = ((Label)e.Row .FindControl("lblname")).Text;
}
Can you hlep me please to find the control, thank you.

Ya, i got the answer, i have to place
string empid = "";
if (e.Row.RowType == DataControlRowType.DataRow)
{
empid = ((Label)e.Row.FindControl("lblname")).Text;
}
then i we get the control

Find control for Data rows only Like:
protected void mygrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string empid = "";
empid = ((Label)e.Row .FindControl("lblname")).Text;
}
}

The "Object reference to instance of an object" error is probably because no control named lblname was found for the current row.
Maybe you need to check the type of the row, e.Row.RowType = DataControlRowType.DataRow so that you are not searching for the control in the header row.

Label lbl = (Label)e.Row.Cells[2].FindControl("lblCreatedBy");
lbl.Text = "ABC";

Related

Retrieving a Dynamically Generated TextBox Content in a GridView in ASP.NET

I have the following RowDataBound method for GridView2
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
List<TextBox> list = new List<TextBox>();
if (ViewState["Table"] != null)
Assessments = (DataTable)ViewState["Table"];
int count = 1;
foreach (DataRow row in Assessments.Rows)
{
TextBox txt = new TextBox();
txt.ID = "AsTxt";
txt.Text = string.Empty;
txt.TextChanged += OnTextChanged;
e.Row.Cells[count].Controls.Add(txt);
count += 2;
listd.Add((e.Row.DataItem as DataRowView).Row[0].ToString() + "Txt");
}
}
}
And the following event (Button Click) to retrieve whatever written in the text box in the GridView
protected void CalculateBtn_Click(object sender, EventArgs e)
{
GridViewRow rr = GridView2.Rows[0];
TextBox rrrr = (rr.FindControl("AsTxt") as TextBox);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + rrrr.Text + "')", true);
}
I always get NullReferenceException. That mean the TextBox object (rrrr) is null always. I am sure that the text object sits in GridView2.Rows[0].
Why is this happening?
This is known issue with the Dynamical created controls in asp. So if you want to use the created control on your postback then I suggest that you declare your controls outside the page_int and do your initialization in the init then use them with their name instead of find control.
Look at this blog this might help you
http://techbrij.com/retrieve-value-of-dynamic-controls-in-asp-net

Change values of a single column of a databound gridview and display it in the same gridview

Its a weird requirement but, Can I alter values of a single column of a databound gridview and display it in the same gridview ? Say, in GridView_RowDataBound(object sender, GridViewRowEventArgs e). I have edited the code for what I am actually doing. Problem is "DataItem" is a typeof class(entity fetched db table) and converting it to Datarow is not possible. So how do i go about it?
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView drv = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (drv["Id"] != DBNull.Value)
{
string val = CommonUtil.Decrypt(drv["Id"].ToString());
e.Row.Cells[3].Text = val ;
}
}
}
Yes it's doable in GridView RowDataBound something like:
if(e.Row.RowType==DataControlRowType.DataRow)
{
//say you want to set value of 3rd column to "Hello"
// e.Row.Cells[2].Text="Hello"; //0 based index
MyCustomClass myitem= (MyCustomClass) e.Row.DataItem;
if (myitem.Id != null)
{
string val = CommonUtil.Decrypt(myitem.Id.ToString());
e.Row.Cells[3].Text = val ;
}
}
If that doesn't help, please share some code and more information on exactly what column you want to change and to what value.
You can cast to the type you want:
MyCustomClass drv = (MyCustomClass) e.Row.DataItem;

how can get column value in row edit event of gridview

This is my editing code in rowdatabound event.
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList dl = (DropDownList)e.Row.FindControl("Sectionname");
comp.MEDIUM = Convert.ToString(e.Row.FindControl("Medium"));
comp.CLASSNAME = Convert.ToString(e.Row.FindControl("ClassName"));
comp.ACADAMICYEAR = Convert.ToString(e.Row.FindControl("AcademicYear"));
DataTable worktype = inter.bindsectionforgird(comp);
dl.DataSource = worktype;
dl.DataTextField = "SectionName";
dl.DataValueField = "SectionId";
dl.DataBind();
}
}
still I am not able to get the value of those fields.
I suggest you to write your code in RowDataBound event
void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Write your code here
}
}
And you can find your Grid's columns as
e.Row.FindControl("yourControlID")
You can see detail in
MSDN reference 1
MSDN reference 2
CodeProject

second page does not fetch correct data in C#

First page :
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var firstCell = e.Row.Cells[0];
firstCell.Controls.Clear();
firstCell.Controls.Add(new HyperLink { NavigateUrl = "ser_job_status1.aspx?Complaint_No = " + firstCell.Text, Text = firstCell.Text, Target = "_blank" });
Session["Complaint_No"] = firstCell.Text;
}
}
Second page :
protected void Page_Load(object sender, EventArgs e)
{
string strComplaintNo = Convert.ToString(Session["Complaint_No"]);
TextBox51.Text = strComplaintNo;
}
TextBox.51.Text of my second page fetches value from First page session.
My problem is my textbox51.text fetches value of Complaint_No which is bound finally to gridview rather fetching my hyperlinked value..
Kindly help to solve this issue..
Session["Complaint_No"] = firstCell.Text; is set in your session, so value of firstCell.Text must be fetched in the second page.
change
Session["Complaint_No"] = firstCell.Text;
to
Session["Complaint_No"] = ((HyperLink)firstCell.Controls[0]).NavigateUrl;

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