Question

asp.net c# find label in gridview

Asked by: fwstealer

I am binding a gridview on the aspx file and am trying to get the value of a label in the code behind.
i'd like to put the value in a global variable so I can use it else where in the code page.


How do I go about it? See my code below.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                                                        CellPadding="4" DataKeyNames="PatientId" DataSourceID="SqlDataSource2" 
                                                        ForeColor="#333333" GridLines="None" Width="100%">
                                                        <RowStyle BackColor="#EFF3FB" />
                                                        <Columns>
                                                            <asp:BoundField DataField="PatientId" HeaderText="PatientId" 
                                                                InsertVisible="False" ReadOnly="True" SortExpression="PatientId" Visible="false" />
                                                            <asp:BoundField DataField="UserId" HeaderText="UserId" 
                                                                SortExpression="UserId" Visible="false" />
                                                        <asp:TemplateField HeaderText="First Name">
                                                            <ItemTemplate>
                                                            <asp:Label ID="lblFName" runat="server" Text='<%# Bind("patFName") %>'></asp:Label>
                                                            </ItemTemplate>
                                                        </asp:TemplateField>
 
Code Behind:
public partial class addrec: System.Web.UI.Page
{
    # region MemberDeclaratives
       public string fname = String.Empty;
    #endregion
 
protected void Page_Load(object sender, EventArgs e)
    {
      Label lbl = this.GridView1.FindControl("lblFName") as Label; //this yields a null value
 
    }
 
protected void btnAdd_Click(object sender, EventArgs e)
    {
     LoadData();      
  //send email
        EmailNotification();
}
 
protected void EmailNotification()
    {
      Label lbl = this.GridView1.FindControl("lblFName") as Label; //this yields a null value
//want to use the value in an email message.
msg.Body = "Hello, " + lbl.ToString();
 
}

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-05-13 at 17:04:44ID24406977
Topics

Programming for ASP.NET

,

Microsoft Visual C#.Net

Participating Experts
4
Points
500
Comments
48

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Binding Data in Gridview from List<object>
    Hi, I am working on web application using ASP.Net, C#, MS SQl- 2005 I am facing problem in binding the data to gridview There is a method in my DataAccess method which returns List of all users present in the database My method is public List<Users> LoadUsersList()...
  2. Binding GridView with sting[]
    Hi i am trying to bind GridView with a sting[] , along with this the property of GridView AutoGenerateColumns="false" , i want to display the data using with fields like BoundFields ,TemplateFileds ,CheckBox , ImageField , ButtonFields etc . plese help me my code ...
  3. Gridview
    My gridview is bound to sqlDataSource I want that when user click on Edit the value of Label 6 will appears in textbox "Timeworked". at the moment when i select edit the textbox "Timeworked" has Null value <asp:TemplateField HeaderTe...
  4. Bind XMLNode to ASP.Net GridView
    I'm having difficulties binding a XMLNode to gridview. If i use a xmlnodereader and read it into a dataset, the dataset has 4 tables. How can i bind the dataset to the gridview to show all the info from the 4 tables? Basically i wish to display the vehicle spec information in...
  5. Gridview total
    Hiii... I have One small asp.net aplication . in this gridview is bounded but column is dynamically created ie ) table which bound the gridview that is created at runtime so please help me to do total in footer...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: abelPosted on 2009-05-13 at 17:35:22ID: 24380887

It is not very useful to put the label into a global variable, because you never know beforehand how many labels you are going to get: it is dependent on the amount of rows.

For the same reason, using FindControl on the GridView will not yield the required results: the GridView will contain many such labels once it is loaded.

Instead, you should use the RowDateBound event, which occurs for each Row when the data is bound to that row. See example code:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    Label lbl = e.Row.FindControl("lblFName") as Label;
    lbl.Text = "you are at row nr. " + e.Row.RowIndex;
}

                                              
1:
2:
3:
4:
5:

Select allOpen in new window

 

by: M3mph15Posted on 2009-05-13 at 17:45:59ID: 24380931

Hi,

I don't know wether the gridview would be showing the data in Page_Load() i agree with abel and use the RowDataBound

 

by: fwstealerPosted on 2009-05-13 at 17:52:17ID: 24380956

The gridview returns the row per a recordid. The user is supposed to select a name from a drop down. this then populates the gridview. the user completes a form and the form is sent to an email address.

so how do i use that to call the method: EmailNotification()?

 

by: fwstealerPosted on 2009-05-13 at 18:03:08ID: 24380996

Would this work?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    Label lblfname = e.Row.FindControl("lblFName") as Label;
    Label lbllname = e.Row.FindControl("lblLName") as Label;
   
EmailNotification(lblfname, lbllname);
}

protected void EmailNotification(string fname, string lname)
{

}

 

by: ddayx10Posted on 2009-05-13 at 18:03:49ID: 24380999

The question for me here is where are you putting the button? Yes you would use rowdatabound to get at the label as a control and its subsequent properties, but that does nothing for you as far as taking action and sending an email based on the label's contents as it seems you want to do.

One idea would be to put a button in each row of the gridview along with the label. The button's value would be something like "Send Email". Now you would also use the CommandText of said button and Databind a value to that such as the label's text (you could bind gridview row index value, or whatever works for your purpose). This CommandText binding could be done inline in the html or using the rowdatabind process.

Now on the buttonclick you can evaluate the sender by converting it to a button and getting it's CommandText field. Viola....

Another way to go about this would be to make the label a link. Assign js to the link that calls postback passing in the value of the label. Or with a little js manipulation there are numerous possibilities.

dday

 

by: fwstealerPosted on 2009-05-13 at 18:06:52ID: 24381012

Actually, I need to take data from two gridviews and send the data in an email.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    Label lblfname = e.Row.FindControl("lblFName") as Label;
    Label lbllname = e.Row.FindControl("lblLName") as Label;
}

protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    Label lblspecname = e.Row.FindControl("lblFName") as Label;
    Label lblspecnumname = e.Row.FindControl("lblLName") as Label;
}


protected void EmailNotification()
{

msg.Body += fname + " " + lname;
msg.Body += specname + " " + specnumname;
}

 

by: ddayx10Posted on 2009-05-13 at 18:15:02ID: 24381041

So now you have the label during the binding process. Are you going to send email for every row? Or do you need to use that information within the context of some user interaction like a button press or ? It is my guess that here you want to have the user select a particular row, and use data from that row to send an email? Lay out a little further what you would like to do please, or maybe you are saying you solved your problem already?

dday

 

by: fwstealerPosted on 2009-05-13 at 18:25:44ID: 24381096

here is how it works:
page loads with 2 drop downs and 2 gridviews
1. ddl1 fname/lname - the user selects one and gridview1 is populated
2. ddl2 specname/specnumname - the user selects one and gridview2 is populated
3. the user types in a value for a textbox
4. the user checks a radio button
5. user clicks the submit button
6. EmailNotification() is fired and the user is redirected to a confirm page

 

by: ddayx10Posted on 2009-05-13 at 19:01:49ID: 24381243

Sorry to keep asking questions, but I need a bit more. You mentioned you needed the values from a label (or maybe two labels) to send the email. So the question is what information do you need to pass on when the user clicks the submit button? A label from a row that the user has interacted with? Some control value in grid1 and some other control value from grid2? Ideas are coming to me, but I gotta know what I'm trying to pass to the server for sending email.

dday

 

by: fwstealerPosted on 2009-05-13 at 19:13:49ID: 24381288

I just need to grab values from both gridviews, other form fields and send it all in one email. I wish this was possible.

protected void EmailNotification()
{

msg.Body += GridView1.FindControl("lblFName").ToString() + " " + GridView1.FindControl("lblLName").ToString() + "<br />";
msg.Body += GridView2.FindControl("lblspecname").ToString() + " " + GridView2.FindControl("lblspecnumname").ToString() + "<br />";

}

 

by: fwstealerPosted on 2009-05-13 at 19:21:20ID: 24381318

gridview1 -
<asp:TemplateField HeaderText="First Name">
                                                            <ItemTemplate>
                                                            <asp:Label ID="lblFName" runat="server" Text='<%# Bind("FName") %>'></asp:Label>
                                                            </ItemTemplate>
                                                        </asp:TemplateField>

is how I've set up the items that i need to get the values of.

 

by: ddayx10Posted on 2009-05-13 at 19:37:37ID: 24381391

*** "I wish this was possible." ***

Yes I understand, but it's not. For example there is (1) instance of lblFName for each row in your gridview. ASP renders that out in html by giving each label a uniqueID (ctl00_item00_lblFName, ctl00_item01_lblFName, etc). So when you look for lblFName it simply doesnt exist. What you need to know is the id of the label on the row you want.

So you have to be strategic about how to get that information. You might be able to tie into some gridview server side events, but I think I would leverage js here instead. What you are trying to do is not for the squeemish, but eminently do-able.

Before I try to get into that though. I notice that in your example all you want is the names and specnumname for your email. If this is the case then why not get those values from the drop downs you mentioned before instead of the gridviews?

If you need actual values from the gridview rows being interacted with then that is more involved.

You mentioned that the user types in a value for a textbox. Is that textbox in gridview1 on the row of the labelFName, or is that textbox standing alone outside the gridview? Same question for the checkbox where is it in relation to gridview1/gridview2? Do these controls even have relations with respective gridviews?

dday

 

by: fwstealerPosted on 2009-05-13 at 19:47:44ID: 24381431

Me too. No doubt - not for squeemish.
For each gridview there is only one row of data. There are other gridview values that I need to obtain - just didn't feel like typing those in as well, like address, phone, etc..

The textbox and checkbox are fortunately outside of the gridviews so I can handle getting that data. No relations with the gridviews.

This is a tough one for me.

 

by: fwstealerPosted on 2009-05-13 at 19:55:49ID: 24381457

another twist - there is even a 3rd gridview that may or may not be present - depends on a data value in the data that is populating gridview1.

so there is gridview1, gridview2 and gridview3 is based on a data element from gridview1. So i need to determine if gridview3 is present and use a field from it.

:)

 

by: ddayx10Posted on 2009-05-13 at 20:17:10ID: 24381509

Ok so I am going to try to give you an easy out (relatively speaking).

If your gridviews each only have one row, and you want to get ahold of controls inside of that row then on your button_click event you can simply get the controls from the gridview thusly:

string test = gv.Rows[0].Cells[0].FindControl("btnInside").Text
//substitute "btnInside" for id of your control.

if you know the index position of your controls you could also find then that way:

gv.Rows[0].Cells[0].Controls[0] //this would give you the first control Controls[1] would give you next etc

That should make it much easier to manage.

dday
 

 

by: ddayx10Posted on 2009-05-13 at 20:19:59ID: 24381523

For the 3rd gridview that is easy enough to incorporate

if(gridview3.rows.count > 0)
{ //do stuff }

dday

 

by: ddayx10Posted on 2009-05-13 at 20:29:08ID: 24381551

Lastly, I should have mentioned that in your gridview that you posted above you will have to manipulate the cells index to get at the control you want OR you can even make that shorter and skip the cells altogether:

string test = gv.Rows[0].Cells[2].FindControl("btnInside").Text

OR

string test = gv.Rows[0].FindControl("btnInside").Text

dday

 

by: fwstealerPosted on 2009-05-13 at 20:43:53ID: 24381594

       string test = GridView1.Rows[0].FindControl("lblFName").Text;
Is not valid.

        string test = GridView1.Rows[0].FindControl("lblFName");
Can't convert to string.

So if i place this code on the event button, how do I pass it to the email method?
protected void btnAdd_Click(object sender, EventArgs e)
    {
        string test = GridView1.Rows[0].FindControl("lblFName");

        //send email
        EmailNotification(test, etc...);

 

by: ddayx10Posted on 2009-05-13 at 21:06:09ID: 24381659

OK,

I tested that out, but I just used a project I had built here in vb that was already binding to a gridview. I converted the vb to c#, but stupid vb does implicit casting sometimes for me and c# will be mad if I missed that.

Just start by getting the control and seeing what you have. The debugger is your friend here. The reason the 2nd one didnt work looks like because you are trying to put a control into a string variable. Change that:

button test = GridView1.Rows[0].FindControl("lblFName");
string test2 = test.Text;

I know this works because I set it up and tested it. If you get an error examine it in the debugger and figure out what's off. Is a header row being caught as Row[0] and you need to use Row[1]? I dunno examine the rows property to see what you have there.

Anyway, once you get all the values you want you will have to change the signature of your email function to accept more arguments and pass them in, much like you have in your example to me.

Hope your making progress, good luck,

dday

 

by: GeoffSuttonPosted on 2009-05-14 at 04:42:11ID: 24383740

Is there any reason why you cannot use GridView1.OnRowDataBound() ?  That will give you each row as it is bound, and the data going into that row.  Then you can use if(e.Row.RowType==RowType.Header) or whatever Rowtype you are searching for.  You can easily extract the data being posted here, or can even use ((Label)e.Row.FindControl("lblFName")).Value to get the data you are looking for.

Geoff

 

by: fwstealerPosted on 2009-05-14 at 04:47:57ID: 24383779

       Button test = GridView1.Rows[0].FindControl("lblFName") as Button; // null value
        String test2 = test.Text.ToString(); //Object reference not set to an instance of an object.

switched to use rows[1] and it bombed.

 

by: GeoffSuttonPosted on 2009-05-14 at 04:59:43ID: 24383853

Oops... sorry - Had only read the first part of the question, then the last comment.  If I understand correcly, you want to A) select a name form a dropdown list, B) Fill the grid based on the name selected, C) Send an email based on the contents in the grid?  

When you fill the grid you are looking to edit the values in the grid, correct?  Is the grid being filled with individual data based on the name being selected, then the email being sent as soon as the name is chosen?

Geoff

 

by: fwstealerPosted on 2009-05-14 at 05:00:50ID: 24383865

this seems to work
        Label test = GridView1.Rows[0].FindControl("lblFName") as Label;
        string test2 = test.Text.ToString();
        EmailNotification(test2);

would like to do this to shorten it but it failed
 Label test = GridView1.Rows[0].FindControl("lblFName") as Label;
        //string test2 = test.Text.ToString();
        EmailNotification(test);
cannot convert from 'System.Web.UI.WebControls.Label' to 'string'

I'm not sure how to use the example geoff; i converted all the data elements to labels.

 

by: fwstealerPosted on 2009-05-14 at 05:02:18ID: 24383876

the grids are being filled with individual data based on the name being selected, then the email being sent
yes

 

by: GeoffSuttonPosted on 2009-05-14 at 05:03:54ID: 24383888

EmailNotification((Label)GridView1.Rows[0].FindControl("lblFName")).Text);
This would work,

Geoff

 

by: fwstealerPosted on 2009-05-14 at 05:05:46ID: 24383900

So I'll have to do this for every data element I need

protected void btnAdd_Click(object sender, EventArgs e)
    {
        Label gpfname = GridView1.Rows[0].FindControl("lblFName") as Label;
        Label gplname = GridView1.Rows[0].FindControl("lblLName") as Label;

        string pfname = gpfname.Text.ToString();
        string plname = gplname.Text.ToString();

EmailNotification(pfname, plname);
}

protected void EmailNotification(string pfname, string plname)
{
//send mail
}

 

by: GeoffSuttonPosted on 2009-05-14 at 05:05:55ID: 24383903

Oops... Missing a bracket...

EmailNotification(((Label)GridView1.Rows[0].FindControl("lblFName")).Text);

 

by: fwstealerPosted on 2009-05-14 at 05:08:29ID: 24383927

       EmailNotification((Label)GridView1.Rows[0].FindControl("lblFName")).Text);
invalid expression term and I'll need to do that for each data element?

 

by: abelPosted on 2009-05-14 at 05:09:56ID: 24383941

> cannot convert from 'System.Web.UI.WebControls.Label' to 'string'

you can use what's above in GeoffSutton post.

Are you trying to send an email for every single row in the grid? There may be an easier way to do that. In fact, unless you truly only want the very first row (check whether it is null, your code will raise nullpointerexceptions whenever the data is empty), you should really resort to another technique.

 

by: abelPosted on 2009-05-14 at 05:12:39ID: 24383961

> invalid expression term and I'll need to do that for each data element?

hopefully not. If you want to do this for each data element, a much easier way is to use the earlier mentioned OnRowDataBound. Every row will pass by there, the data is set, the text of the label is set and you can send your mail with two lines of code.

If, for whatever reason, you do not want to do that, you can use other techniques to get an array of all labels that go by that name. Alternatively, consider passing in the DataGridViewRow object to the EmailNotification, that will make your code much cleaner and easier to read.

 

by: GeoffSuttonPosted on 2009-05-14 at 05:17:15ID: 24384006

Since emailNotification is taking 2 arguments, you would need to use:
EmalNotification(((Label)GridView1.Rows[0].FindControl("lblFName)).Text,((Label)GridView1.Rows[0].FindControl("lblLName")).Text)

If you want to use that on each row, using the button click, use

ForEach(GridViewRow row in GridView1.Rows){


 If(row.RowType==RowType.DataRow){

  EmailNotification((Label)row.FindControl("lblFName")).Text,row.FindControl("lblLName").text);

 }

}

 

by: abelPosted on 2009-05-14 at 05:19:15ID: 24384029

So, in short, and while keeping the current approach (you'll change it someday, I'm sure) change the EmailNotification as follows:

// inside your btnAdd_code click, getting all the rows as follows:
protected void btnAdd_Click(object sender, EventArgs e)
{
    foreach(GridViewRow row in GridView1.Rows)
    {
        EmailNotification(row);
    }
}
 
public void EmailNotification(GridViewRow row)
{
    string pfname = "";
    string plname = "";
    Label gpfname = (Label) row.FindControl("lblFName");
    Label gplname = (Label) row.FindControl("lblLName")
 
    if(gpfname != null && gplname != null)
    {
        pfname = gpfname.Text;
        plname = gplname.Text;
    }
    // put your original mail notification code here
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:

Select allOpen in new window

 

by: GeoffSuttonPosted on 2009-05-14 at 05:19:24ID: 24384030

Depend on the CTRL+Space to give you the exact terms to use.  This is just typed in from member, so copying this into your code isn't going to be accurate:)  Also you shouldn't need to us .ToString() since the .Text is already a string value.

Geoff

 

by: fwstealerPosted on 2009-05-14 at 05:38:40ID: 24384204

okay this seems to work:
 
protected void btnAdd_Click(object sender, EventArgs e)
    {
        EmailNotification(((Label)GridView1.Rows[0].FindControl("lblFName")).Text,
            ((Label)GridView1.Rows[0].FindControl("lblLName")).Text,
            ((Label)GridView1.Rows[0].FindControl("lblAddress1")).Text,
            ((Label)GridView1.Rows[0].FindControl("lblCity")).Text,
            ((Label)GridView1.Rows[0].FindControl("lblState")).Text,
            ((Label)GridView1.Rows[0].FindControl("lblZip")).Text,
            ((Label)GridView2.Rows[0].FindControl("lbldocFName")).Text,
            ((Label)GridView2.Rows[0].FindControl("lbldocLName")).Text,
            ((Label)GridView2.Rows[0].FindControl("lblAddress1")).Text,
            ((Label)GridView2.Rows[0].FindControl("lblAddress2")).Text,
            ((Label)GridView2.Rows[0].FindControl("lblCity")).Text,
            ((Label)GridView2.Rows[0].FindControl("lblState")).Text,
            ((Label)GridView2.Rows[0].FindControl("lblZip")).Text,
            ((Label)GridView2.Rows[0].FindControl("lblOfficeFax")).Text,
           ((Label)GridView3.Rows[0].FindControl("lblPIC")).Text,
          ((Label)GridView3.Rows[0].FindControl("lblPICName")).Text,
          ((Label)GridView4.Rows[0].FindControl("lblSIC")).Text,
         ((Label)GridView4.Rows[0].FindControl("lblSICName")).Text);
}

 protected void EmailNotification(string pfname, string plname, etc....)
{

}

However, my biggest issue is below:
Gridview1 is always present
Gridview2 is always present

Gridview3 may or may not be present
Gridview4 may or may not be present

So how do I handle that issue?

 

by: abelPosted on 2009-05-14 at 05:42:40ID: 24384242

> okay this seems to work:

can you take a moment and check my code? It may help you a lot. The code you are posting is terrible to maintain. It is your choice, of course, but anyway. And why only Rows[0]? Were we mistaken that you wanted all rows, like you said earlier?

It is quite awkward to send so many parameters to a function. In object oriented programming, you make your life easier if you send objects to functions. In this case, sending only the row to EmailNotification will make your code much cleaner.

Whether GridView3 or 4 are not present is not important. They will be accessible regardless whether they are hidden or not. Change my approach slightly to deal with data that is not present for a certain row.

In case you want to know regardless:

if (GridView3.Visible)
{
  ... your code ..

 

by: fwstealerPosted on 2009-05-14 at 05:59:07ID: 24384397

abel,

the last bit of code worked; however, how do i account if gridview 3 and 4 are not present?

 

by: fwstealerPosted on 2009-05-14 at 06:02:20ID: 24384421

when i mention that gridview 3 and 4 might not be present it means that they have 0 rows per the id related from the 1st drop down.

so ddl fname, lname id1
gridview1 is populated based on id1
gridview3 may be populated if there is a row of data linked to id1
same for gridview 4

also, how do i send over multiple gridviews with
foreach(GridViewRow row in GridView1.Rows)
    {
        EmailNotification(row);
    }

 

by: abelPosted on 2009-05-14 at 06:15:38ID: 24384554

The nice thing about the for-each is that it automatically won't run at all if the Rows are empty. That means,in your situation, if you want to call EmailNotification for each row, that you can do the following (don't misinterpret the "new" keyword, it is only needed for the array, it does not create new gridviews):


foreach(GridView gv in new GridView[] {GridView1, GridView2, GridView3, GridView4})
{
    foreach (GridViewRow row in gv.Rows)
    {
        EmailNotification(row);
    }
}
                                              
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window

 

by: abelPosted on 2009-05-14 at 06:16:19ID: 24384562

So, in other words, the above code will run through all Rows of all your gridviews, whether those gridviews have rows or not.

 

by: GeoffSuttonPosted on 2009-05-14 at 06:17:33ID: 24384575

abel:  Don't forget to include checking row.RowType.  Otherwise you will be getting errors from the header rows.

Geoff

 

by: abelPosted on 2009-05-14 at 06:20:12ID: 24384601

thanks for pointing that out. GeoffSutton. You can do so in several ways (i.e., using LINQ for one), but let's keep it simple:

foreach(GridView gv in new GridView[] {GridView1, GridView2, GridView3, GridView4})
{
    foreach (GridViewRow row in gv.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            EmailNotification(row);
        }
    }
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

Select allOpen in new window

 

by: fwstealerPosted on 2009-05-14 at 06:32:55ID: 24384749

so much for my mess - what i was thinking

protected void btnAdd_Click(object sender, EventArgs e)
    {

if (GridView1.Visible = true && GridView2.Visible = true)
        {
            //gridview1 and gridview2 are visible with data

            if (GridView3.Visible = true && GridView4.Visible = true)
            {
            //gridview3 and 4 are visible with data
      //send over gridview1,2,3,4
            }
            else
            {
                //gridview3 is visible with data and gridview4 is not visible
      //send over gridview1,2,3
            }
        }

 

by: fwstealerPosted on 2009-05-14 at 06:49:42ID: 24384943

protected void btnAdd_Click(object sender, EventArgs e)
    {
foreach (GridView gv in new GridView[] { GridView1, GridView2, GridView3, GridView4 })
        {
            foreach (GridViewRow row in gv.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    EmailNotification(row);
                }
            }
        }


}

protected void EmailNotification(GridViewRow row)
    {
        string pfname = "";
        string plname = "";
        string dfname = "";
        string picname = "";
        string sicname = "";
        Label gpfname = (Label)row.FindControl("lblpFName"); //gridview1
        Label gplname = (Label)row.FindControl("lblpLName"); //gridview1
        Label gdfname = (Label)row.FindControl("lbldFName"); //gridview2
        Label gpicname = (Label)row.FindControl("lblpicName"); //gridview3
        Label gsicname = (Label)row.FindControl("lblsicName"); //gridview4

           pfname = gpfname.Text;
            plname = gplname.Text;
            dfname = gdfname.Text;
            picname = gpicname.Text;
            sicname = gsicname.Text;


It is only picking up data from gridview1 and not the other gridviews. yes, gridview2, 3 and 4 have data.

 

by: abelPosted on 2009-05-14 at 09:17:38ID: 24386540

> so much for my mess - what i was thinking

you were mixing "=" and "==" in that post. Anyway, getting boolean logic right is not easy...

> It is only picking up data from gridview1 and not the other gridviews. yes, gridview2, 3 and 4 have data

sounds like we're getting somewhere. Can you try the following and show me what the Immediate window shows (you may need to add a "using System.Diagnostics;" on top of your class)?

foreach(GridView gv in new GridView[] {GridView1, GridView2, GridView3, GridView4})
{
    Debug.WriteLine(gv.ID + " has " + gv.Rows.Count + " rows";
    foreach (GridViewRow row in gv.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            EmailNotification(row);
        }
    }
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

Select allOpen in new window

 

by: ddayx10Posted on 2009-05-14 at 16:03:12ID: 24390786

whew seems like you've been busy while I was away....but making progress, cool

dday

 

by: abelPosted on 2009-05-14 at 16:51:33ID: 24391139

lol, different timezones. bedtime for me, you may take over :)

 

by: fwstealerPosted on 2009-05-16 at 08:25:09ID: 24402973

I'll get back to this shortly; thanks for helping

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...