Tuesday, June 2, 2009

How to extract data out of your datacontrol (asp.net formview, detailsview or gridview) using FindControl or ExtractValuesFromCell method?

Most of the times asp.net programmers need to extract data out of the asp.net datacontrols like formview, detailsview or gridview. Mostly we use FindControl method of the data control for this purpose. And another method ExtractValuesFromCell is also entertained to achieve the goal. It would be very interesting to throw a little light upon both of them.

Naturally I am familiar with the FindControl method of the datacontrols. For example, to find a dropdownlist in the formview or detailsview control, I would call:

DropDownList ddlTest=FormView1.FindControl("DropDownList1") as DropDownList;

Similarly, we could search for an asp.net control in a particular row of a gridview control. For example:

GridViewRow row=GridView1.Rows[5]; // here we are dealing with the fifth row
TextBox textName=row.Cells[2].FindControl("textboxName") as TextBox; //here, there is a textbox with id textboxName in the second cell of the row
if(textName!=null) //check if such textbox was found in the specified cell or the specified row
{
string name=textName.Text;
}

Practically we need to get a control from the data control in special events of the control like inserting, inserted, updating, updated, deleting, deleted, selectedindexchanging, selectedindexchanged etc. Combining the FindControl method with such event handlers help customize data during data operations (add,edit,delete) and provides flexibility to display data from database or other data sources (xml, csv, programmatically created datatables etc).

Before discussing ExtractValuesFromCell, I would like to drop one note. Please note that some standard controls in some data controls may be available for extracting only in the particular mode of the data controls. Confusing? Don't worry. This simple example will clarify it. Say, we do have a textbox in the edititemtemplate of a detailsview. To reference this textbox and extract value from it, we can use the findcontrol method only if we are in edit mode. In other modes we will get null reference (and possibly null reference exception may be thrown when we try to extract text or other properties). That is why I have checked for the null in the code above before reading text value from the textbox.

Now let's focus on ExtractValuesFromCell. There goes a popular article on Extracting data out of your datacontrol which discusses ExtractValuesFromCell method to get data from the controls in datacontrols like gridview, formview or detailsview. (The title of this article is inspired from it! And I have tried to make it as useful as I can). Please refer to the heavily discussed article to understand what the author davidfoul has discovered and what are the benefits of using ExtractValuesFromCell method to extract data out of a datacontrol.

After you have been through the article, you sure would like to ask which method to use- FindControl or this ExtractValuesFromCell? This is what I commented to the author:

Hi dear author,

I came here following the discussion on the asp.net forum: forums.asp.net/.../1362718.aspx

I have always been using FindControl() method: much easier and handy. You need not to write (and call everytime) the functions to extract values (or cells) using ExtractValuesFromCell.

This ExtractValuesFromCell way of extracting values from cell is just another way around it. So what's wrong to go with FindControl. Please give your opinion (perhaps you could update the post to add a sections: Why to not use FindControl(); I am requesting this because the argument among developers would go longer!).

Hey, this could be the advantage: People sometimes ask how to get all the values from my gridview since I have been editing and updating it, so changing the original value from the datasource. In such case this trick could help a lot.

Thanks.

And our generous author davidfoul has replied his kind views:

@sangam100 I had this same question about FindControl on the forum. Here is what I said:

It's not the use of FindControl that makes my spine tingle its the MISuse and ABuse of it that does. FindControl is a good method and very useful, but look at the name of method, FindControl. Everything has a purpose right? If I'm trying to find a control then i'll call find control. If I'm trying to get data out of a control I might call find control or some other API that is better at getting data, i.e ExtractRowValues. I think that there is alot of knowledge out there, good and bad, about using these data controls and I just want to try to set some things straight by shedding some more light on how stuff works (I love that website).

Before I go lemme show you what I mean by picking the right API.  Lets make a new control IntControl. IntControl has a method int GetValue(). Now OO principals tell us to not break the abstraction by letting consumers grab at the internals but IntControl derives from control, and by default, there is alot of other things exposed to the consumer that shouldn't be. Now we know that IntControl uses a textbox internally so I could never call GetValue and instead write:

int value;

Int32.TryParse(((TextBox)IntControl.Controls[0]).Text, out value);

Everything will work fine until the author of IntControl decides to use a div instead of a textbox.

The REAL lesson to take away from the blog post is to try your best to follow the contract provided by a class or an interface (in this case the DataControl).

You can read comments, views, suggestions of so many enthusiastic asp.net web developers both in the original site by the author and a post in the forums.asp.net/.../1362718.aspx. Please comment in the respective sites to put your opinions to the articles. However you can comment as always on this article regarding my perspectives. Thank you. Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

Monday, June 1, 2009

How to send email from asp.net? Basic C# code to send simple email

Sending email in asp.net is very useful and customizable too. The powerful classes help you compose and send email in minute! The glamour has always fascinated me, but more important is the frequent questions that are asked in asp.net related forums on sending email in asp.net using C# or vb.net. We can send email using some smtp server. And if this is not viable (sometimes we don't have smtp accounts!) we can use our own gmail account to send email (Thank you gmail!)

Take one example- Here goes the question that was asked in asp.net forum-

"can someone give me code how to send an e-mail from c# code
I am working with a company using Microsoft outlook for my mails.
I want to send mail only to 1 person, also please help me in identifying "smtp hostname"
"

Here goes the simple and helpful answer.

Visiting all above listed links you must have realized that sending email in asp.net is quite fun and useful too. In fact, a lot of customizations exist depending on your requirement. My suggestion is to do the basic email sending first. After that you can play with the classes and objects to perform more actions. Let me show you the basic email sending using c#.

//sending basic mail in asp.net 
public void SendBasicMail()
{
//create new mailmessage object
MailMessage message = new MailMessage(new MailAddress("sangam@test.com"), new MailAddress("anup@best.com"));
message.Body = "Hi. This is test message.";
message.Subject = "Test Message!";
message.IsBodyHtml = false;

//create smtp client and send mail
SmtpClient client = new SmtpClient("mail.mysmtpserver.com", 25);
try
{
client.Send(message);
lblError.Text = "Email sent successfully!";
lblError.ForeColor = Color.Green;
}
catch (Exception ex)
{
lblError.Text = "Email could not be sent. " + ex.Message;
lblError.ForeColor = Color.Red;
}
}

This simple example will help you understand the basics of sending email in asp.net web application.

Now interested in sending email using our own gmail account? Here goes the coding by getchinna_sv (Thank you getchinna_sv! Yours sangam100).

 protected void sendMail()
{
string from = "me@gmail.com"; //Replace this with your own correct Gmail Address
string to = "you@gmail.com"; //Replace this with the Email Address to whom you want to send the mail
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from, "One Ghost", System.Text.Encoding.UTF8);
mail.Subject = "This is a test mail";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "This is Email Body Text";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;

SmtpClient client = new SmtpClient();
//Add the Creddentials- use your own email id and password
client.Credentials = new System.Net.NetworkCredential(from, "Password");
client.Port = 587; // Gmail works on this port
client.Host = "smtp.gmail.com";
client.EnableSsl = true; //Gmail works on Server Secured Layer
try
{
client.Send(mail);
}
catch (Exception ex)
{
Exception ex2 = ex;
string errorMessage = string.Empty;
while (ex2 != null)
{
errorMessage += ex2.ToString();
ex2 = ex2.InnerException;
}
HttpContext.Current.Response.Write(errorMessage);
} // end try
}

client.Credentials = new System.Net.NetworkCredential(from, "Password"); in this statement... write your gmail password.... from address should be a gmail address....

Hope this post will help. Thank you. Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

Dropdownlist selected item validation fails: the suggestion

Today I got across a question in the asp.net forum which seems simple but is still confusing for many beginners. So I am giving a place for it here:

Question:

Hi Everyone,

I'm trying to set some error handling by returning a message when a button is clicked and the user has not selected an item from the dropdown menu. I'm using this but for some reason it is being ignored?

protected void validatebtn_Click(object sender, ImageClickEventArgs e)
{
if (!(DropDownList1.SelectedValue == "Select Item"))
{
lblerrors.Text = "
You have not selected an item from the drop down list.";
}
else
{
//...continue with the code.
}
}

When I debug the code, it reads the first line:

if (!(DropDownList1.SelectedValue == "Select Item"))
and then skips to the else statement and misses my message?

Can anyone advise why this is happening?

Thanks.
Chloe ~X~

Among other suggestions, here is what I have suggested:

Answer:

Looking into your explanation and reading all the answers given by members, some questions came in my mind.

1. Did you check what value is exactly selected from the dropdownlist? I mean DropDownList1.SelectedValue should be "Select Item" only then your comparision will be true.
2. Are you adding this "Select Item" from design view or is it added programmatically from code behind? Did you only specify "text" or both text and value? See the markup below:

<asp:DropDownList ID="ddlTest" runat="server">
<asp:ListItem Text="Select Item" Value="Select Item" Selected="True"></asp:ListItem>
</asp:DropDownList>

If you don't put Selected="true", this item may display at the first position, but is not selected yet. So don't forget to set this. Another thing to notice is you should have set both Text and Value. The "SelectedValue" corresponds to the "Value" in the markup. Only then your code will work. Don't forget to have both text and value if you add listitem to the dropdownlist from codebehind, like this one:

ListItem item = new ListItem("Select Item", "Select Item");
DropDownList1.Items.Add(item);

Hope this helps. Please feel free to ask if the problem persists or if further help is required. Thanks.

kick it on DotNetKicks.com Shout it pimp it

Friday, May 29, 2009

Check uncheck all rows of gridview (select or deselect all rows at once)

The asp.net gridview data control offers lots of features, that we all know. Adding some cool effects may make this control more usable. For instance, we could check or uncheck all the checkboxes in a column of the gridview control. A column [leftmost column usually] consisting of checkbox control is generally used to select a row. Sometimes we may need to check (and uncheck) all the rows of the gridview. Purpose of doing so may be different depending upon the business requirement. And if we need to do so, we can!


Fig. Check Uncheck all rows in a gridview


Let's be quick to implement check/uncheck all the rows of gridview at once in asp.net gridview. Let's have the markup for the gridview first.

<asp:GridView ID="gvTest" Width="100%" runat="server" AutoGenerateColumns="false">

<Columns>

<asp:TemplateField HeaderText="Select" HeaderStyle-HorizontalAlign="center" ItemStyle-HorizontalAlign="center">

<HeaderTemplate >

<input id="chkAll" onclick="javascript:SelectDeselectAllCheckboxes(this);"

runat="server" type="checkbox" />

</HeaderTemplate>

<ItemTemplate>

<asp:CheckBox ID="chkSelect" runat="server" />

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField HeaderText="Name" DataField="Name" ItemStyle-Width="100" />

<asp:BoundField HeaderText="Address" DataField="Address" />

</Columns>

</asp:GridView>

Watched the checkbox control in the header template of the first column? We will use this checkbox to select or deselect all the rows in the gridview. Also mark that clicking this checkbox will call the javascript function SelectDeselectAllCheckboxes. Now is the time to define some javascript snippets to get help from.

<script type="text/javascript">  

function SelectDeselectAllCheckboxes(spanChk){

// Added as ASPX uses SPAN for checkbox



var oItem = spanChk.children;

var theBox= (spanChk.type=="checkbox") ? spanChk : spanChk.children.item[0];

xState=theBox.checked;

elm=theBox.form.elements;

for(i=0;i<elm.length;i++)

if(elm[i].type=="checkbox" && elm[i].id!=theBox.id)

{

//elm[i].click();

if(elm[i].checked!=xState)

elm[i].click();

//elm[i].checked=xState;

}

}

</script>

The task done by the javascript function is simple. It takes the checkbox itself as the input. If it is checked, it searches for all the checkboxes in the gridview and checks them. And reversely, if it is unchecked, all those checkboxes will be consequently unchecked.

There is no need of any codebehind just for this functionality. So I am leaving other parts including databinding code. In fact, for most of the test purposes I do Create DataTable Programmatically and bind the gridview, formview or detailsview to that DataTable.

The only drawback with this technique is that it treats all the checkboxes in or outside the gridview control equal.

You can post your comment, rate this post or add this post to your favourites or share it. Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

Wednesday, May 27, 2009

Fill asp.net formview textbox to initial value in insert mode

In most scenarios, the asp.net data controls like detailsview and formview have empty controls in insert mode. This means any field that requires [or at least expects] user input will not contain any data. But this default configuration sometimes needs to be modified. Say, we would like to fill the date field in a textbox to current date, so that it will be easier for user. This is just an example. This can be the asp.net dropdownlist from where we would like to select one value initially, or it may be other asp.net user input control like checkbox or radiobutton. In such scenario, we can set the control value to some default initial value. With datacontrols like formview and detailsview, it takes a little effort [simple and tricky!]. In this short post [In fact I am expecting to keep this post as such as possible since there is no need of much explanation: concept is crystal clear and implementation is also easy!] I am going to show the simple coding practice to initiate the formview or detailsview control to some value. I will be choosing formview to show the example.


Fig: Setting a textbox to an initial value in insert mode of an asp.net formview control

The formview can have one of three modes at one instance of time. They are Insert, Edit and ReadOnly modes. We should be careful about the current mode of the formview before we do reference any control. This is because a textbox in edit template may not be available in the read only mode, for instance. So we will check the current mode of the formview and search for the textbox with its ID. Then we can easily set the value of the control. Let's have a formview first.

FormsView Design Markup

<asp:FormView ID="FormView1" runat="server" HeaderText="Fill the Credentials below." DefaultMode="Insert">

<ItemTemplate>

<table>

<tr>

<td>

Name: <asp:Label ID="lblName" runat="server"></asp:Label>

</td>

</tr>

<tr>

<td>

Date of Test: <asp:Label ID="lblTestDate" runat="server"></asp:Label>

</td>

</tr>

</table>

</ItemTemplate>

<InsertItemTemplate>

<table>

<tr>

<td>

Name: <asp:TextBox ID="txtName" runat="server"></asp:TextBox>

</td>

</tr>

<tr>

<td>

Date of Test: <asp:TextBox ID="txtTestDate" runat="server"></asp:TextBox>

</td>

</tr>

</table>

</InsertItemTemplate>

</asp:FormView>

We simply have two fields in the formview: name and date of test. Our intension will be to initiate the value of the date of test field to current date.

CodeBehind for the example

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Call to filling textbox in the insert mode;
//I assume here that initially the formview
//is in insert mode
FillDefaultVaueInFormView();
}
}

public void FillDefaultVaueInFormView()
{
//if the formview is in insert mode
if (FormView1.CurrentMode == FormViewMode.Insert)
{
//txtTestDate is the id of the 'date of text' textbox in formview
TextBox txtTest = FormView1.FindControl("txtTestDate") as TextBox;
if (txtTest != null)
{
txtTest.Text = DateTime.Now.ToShortDateString();
}
}
}

Now the formview will have the date of test field initiated to the current date. Let me repeat- Simple and Tricky! You can post your comments and suggestions from the form below. You can rate this post as well. You can even share this post. Just add this post to the social sites! Happy Programming!

kick it on DotNetKicks.com Shout it pimp it

Popular Posts

Recent Articles