Thursday, November 17, 2011

How to Clear All Textboxs, All Dropdowns, All Validators in C#

private void ClearEditCustomerForm()
    {
        //Empty out text boxes
        var textBoxes = new List<Control>();
        FindControlsOfType(this.phrEditCustomer, typeof(TextBox), textBoxes);

        foreach (TextBox textBox in textBoxes)
            textBox.Text = "";

        // Dropdowns

        var dropdowns = new List<Control>();
        FindControlsOfType(this.phrEditCustomer, typeof(DropDownList), dropdowns);
        foreach (DropDownList drop in dropdowns)
        {
            drop.SelectedValue = "0";
        }

        //Clear validators
        var validators = new List<Control>();
        FindControlsOfType(this.phrEditCustomer, typeof(BaseValidator), validators);

        foreach (BaseValidator validator in validators)
            validator.IsValid = true;
    }


    static public void FindControlsOfType(Control root, Type controlType, List<Control> list)
    {
        if (root.GetType() == controlType || root.GetType().IsSubclassOf(controlType))
        {
            list.Add(root);
        }

        //Skip input controls
        if (!root.HasControls())
            return;

        foreach (Control control in root.Controls)
        {
            FindControlsOfType(control, controlType, list);
        }
    }

Thursday, November 10, 2011

How to Get GridView Header Name With Cell Values and Convert to XML

sb.Append("<Results>");
            foreach (GridViewRow item in GridView1.Rows)
            {
                if (item.RowType == DataControlRowType.DataRow)
                {
                    for (int i = 0; i < item.Cells.Count; i++)
                    {
                        sb.Append("<" + GridView1.HeaderRow.Cells[i].Text + ">" + item.Cells[i].Text + "</" + GridView1.HeaderRow.Cells[i].Text + ">");
                    }
                }
            }
            sb.Append("</Results>");

Wednesday, November 2, 2011

Important Sample Applications Links

Grid View Edit, Update, Delete, Cancel

<asp:GridView ID="GrdResult" runat="server" AutoGenerateColumns="False" DataKeyNames="UserId,RoleId" EmptyDataText="No Records to Display"
CellPadding="3" Width="94%" AllowPaging="True" OnPageIndexChanging="GrdResult_PageIndexChanging"
OnRowCancelingEdit="GrdResult_RowCancelingEdit" OnRowDeleting="GrdResult_RowDeleting"
OnRowEditing="GrdResult_RowEditing" OnRowUpdating="GrdResult_RowUpdating" PageSize="20"                             OnRowDataBound="GrdResult_RowDataBound" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellSpacing="2">
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<Columns>
<asp:TemplateField HeaderText="Username">
<ItemTemplate>
<asp:Label ID="LblGUsername" runat="server" Text='<%# Bind("Username") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TxtGUserName" runat="server" Text='<%# Bind("Username") %>'></asp:TextBox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Firstname">
<EditItemTemplate>
<asp:TextBox ID="TxtGFirstname" runat="server" Text='<%# Bind("Firstname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LblGFirstname" runat="server" Text='<%# Bind("Firstname") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Lastname">
<EditItemTemplate>
<asp:TextBox ID="TxtGLastname" runat="server" Text='<%# Bind("Lastname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LblGLastname" runat="server" Text='<%# Bind("Lastname") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="RestOfName">
<EditItemTemplate>
<asp:TextBox ID="TxtGRestOfName" runat="server" Text='<%# Bind("Restname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LblGRestOfName" runat="server" Text='<%# Bind("Restname") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Role">
<EditItemTemplate>
<asp:DropDownList ID="DDLGRoles" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LblGRoleId" runat="server" Text='<%# Bind("RoleName") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" /></asp:TemplateField>
<asp:TemplateField HeaderText="Edit"><EditItemTemplate>
<asp:LinkButton ID="LnkUpdate" runat="server" CommandName="Update">Update</asp:LinkButton>                                            &nbsp;<asp:LinkButton ID="LnkCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>                                        </EditItemTemplate><ItemTemplate>                                           <asp:LinkButton ID="LnkEdit" runat="server" CommandName="Edit" OnClientClick='return confirm("Are you sure want to Edit?");'>Edit</asp:LinkButton>                                        </ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="LnkDelete" runat="server" CommandName="Delete" OnClientClick='return confirm("Are you sure want to Delete?");'>Delete</asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField></Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>
#region Grid
protected void GrdResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GrdResult.PageIndex = e.NewPageIndex;
            BindGrid();
        }

protected void GrdResult_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GrdResult.EditIndex = -1;
            BindGrid();
        }

protected void GrdResult_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GrdResult.EditIndex = e.NewEditIndex;
            BindGrid();
        }

protected void GrdResult_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
                int _Userid = Convert.ToInt32(GrdResult.DataKeys[e.RowIndex].Values[0].ToString());
                TextBox _Username = (TextBox)GrdResult.Rows[e.RowIndex].FindControl("TxtGUserName");
                TextBox _Firstname = (TextBox)GrdResult.Rows[e.RowIndex].FindControl("TxtGFirstname");
                TextBox _Lastname = (TextBox)GrdResult.Rows[e.RowIndex].FindControl("TxtGLastname");
                TextBox _Restofname = (TextBox)GrdResult.Rows[e.RowIndex].FindControl("TxtGRestOfName");
                DropDownList _RoleID = (DropDownList)GrdResult.Rows[e.RowIndex].FindControl("DDLGRoles");
                ObjUsersBL.VoidTextCommand(Convert.ToString(Session["_ConString"]), "Update TblUser set UserName='" + _Username.Text + "', FirstName='" + _Firstname.Text + "',LastName='" + _Lastname.Text + "',RestOfName='" + _Restofname.Text + "',RoleId='" + _RoleID.SelectedValue + "' where UserID='" + _Userid + "' and CenterId='" + Convert.ToString(Session["_SelCen"]) + "'");
                GrdResult.EditIndex = -1;
                BindGrid();
            }
            catch (Exception Ex)
            {
                log.Info("GrdResult_RowUpdating() : ADMIN : FrmMainPage.aspx", Ex);
            }
        }

protected void GrdResult_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
                int _Userid = Convert.ToInt32(GrdResult.DataKeys[e.RowIndex].Values[0].ToString());
                ObjUsersBL.VoidTextCommand(Convert.ToString(Session["_ConString"]), "Update TblUser set Obsolete=1 where UserID='" + _Userid + "' and CenterId='" + Convert.ToString(Session["_SelCen"]) + "'");
                BindGrid();
            }
            catch (Exception Ex)
            {
                log.Info("GrdResult_RowDeleting() : ADMIN : FrmMainPage.aspx", Ex);
            }
        }

protected void GrdResult_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
                    DropDownList _RoleId = (DropDownList)e.Row.FindControl("DDLGRoles");
                    _RoleId.DataSource = ObjUsersBL.SelectDataSet(Convert.ToString(Session["_ConString"]), "Select RoleId,Role from tblRoles");
                    _RoleId.DataTextField = "Role";
                    _RoleId.DataValueField = "RoleId";
                    _RoleId.DataBind();
                    _RoleId.SelectedValue = Convert.ToString(GrdResult.DataKeys[e.Row.RowIndex]["RoleId"].ToString());
                }
            }
            catch (Exception Ex)
            {
                log.Info("GrdResult_RowDataBound() : ADMIN : FrmMainPage.aspx", Ex);
            }
        }
        #endregion

How to Convert Image as Binary and Binary to Image

string StrExtension = Path.GetExtension(FUHeaderLogo.PostedFile.FileName.ToString());
byte[] ImgBinary = System.IO.File.ReadAllBytes(FUHeaderLogo.PostedFile.FileName.ToString());

Method 1

void GetPrescriptionImages(int AppId, int CenterId)
{

DataTable DtImgs = ObjAppointmentBL.GetPrescriptionImages(AppId, CenterId);
if (DtImgs.Rows.Count > 0)
{
Session["PrescriptionUrl"] = DtImgs.Rows[0]["PrescriptionUrl"].ToString();
foreach (DataRow _Row in DtImgs.Rows)
{
string[] _Url = _Row[1].ToString().Split('\\');
string DirectoryPath = System.Web.Hosting.HostingEnvironment.MapPath("~/ScanImagePrescriptions/") + _Url[2].ToString() + "\\";
if (Directory.Exists(DirectoryPath) == false)
{
Directory.CreateDirectory(DirectoryPath);
}
if (!File.Exists(DirectoryPath + _Url[3].ToString()))
{
byte[] _Img = (byte[])_Row[2];
MemoryStream ms = new MemoryStream(_Img);
FileStream fs = new FileStream
 (DirectoryPath + _Url[3].ToString(), FileMode.Create);
ms.WriteTo(fs);
ms.Close();
fs.Close();
fs.Dispose();
}
}
}
else
Session["PrescriptionUrl"] = "";
}

Method 2

void CreateBinayImages(int CenterId, string filename, DataTable DtBinaryImgs)
{
try
{
if (DtBinaryImgs.Rows.Count > 0)
{
string DirectoryPath = filename.Replace("DownLoadReports.pdf", "");
byte[] _Img = (byte[])DtBinaryImgs.Rows[0]["ImgHeaderBinayByte"];
MemoryStream ms = new MemoryStream(_Img);
FileStream fs = new FileStream
 (DirectoryPath + Convert.ToString(CenterId) + DtBinaryImgs.Rows[0]["ImgExtension"].ToString(), FileMode.Create);
ms.WriteTo(fs);
ms.Close();
fs.Close();
fs.Dispose();
}
}
catch (Exception Ex)
{
}
}

Method 3

public void GetLoadedImages()
{
try
{
DataSet DsImages = ObjUsersBL.SelectDataSet(Convert.ToString(Session["_ConString"]), "Select ImgHeaderBinayByte,ImgExtension from tblCentreSelection where Centreid='" + Session["_SelCen"] + "'");
if (DsImages.Tables[0].Rows.Count > 0)
{
string DirectoryPath = System.Web.Hosting.HostingEnvironment.MapPath("~/HeaderLogos/");
byte[] _Img = (byte[])DsImages.Tables[0].Rows[0]["ImgHeaderBinayByte"];
MemoryStream ms = new MemoryStream(_Img);
FileStream fs = new FileStream
 (DirectoryPath + "\\" + Session["_SelCen"].ToString() + DsImages.Tables[0].Rows[0]["ImgExtension"].ToString(), FileMode.Create);
ms.WriteTo(fs);
ms.Close();
fs.Close();
fs.Dispose();
if (File.Exists(DirectoryPath + Session["_SelCen"].ToString() + DsImages.Tables[0].Rows[0]["ImgExtension"].ToString()))
{
ImgView.Visible = true;
ImgView.ImageUrl = "~/HeaderLogos/" + Session["_SelCen"].ToString() + DsImages.Tables[0].Rows[0]["ImgExtension"].ToString();
}
}
}
catch (Exception Ex)
{
log.Info("GetLoadedImages() : ADMIN : ImgHeaderLogoUpdater.aspx", Ex);
}
}