Blocks
Blocks

Reputation: 351

ASP.net 4.6 c# Set text when page opens

I have a page that allows the user to click the generate button to assign a random code to a text box. I want the text box to be assigned a default random code when the page opens. The text that is assigned needs to use the generate code method that the button is using. Where do I assign the text to the box when the page opens? I think it's the onload from the microsoft docs.

for example

// Override the OnLoad method to set _text to
// a default value if it is null.
protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    if (_text == null)
        _text = "Here is some default text.";
}

but I Don't know where to put that.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="XMLAddUpdateDelete.aspx.cs"
    Inherits="xmlInsertUpdateDelete.XMLAddUpdateDelete" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    ID
                </td>
                <td>
                    <asp:TextBox ID="txtID" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Instructor</td>
                <td>
                    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    <asp:TextBox ID="txtDesignation" runat="server" Visible="False"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    CourseID
                </td>
                <td>
                    <asp:TextBox ID="txtEmailID" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Description</td>
                <td>
                    <asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    AttendanceCode
                </td>
                <td>
                    <asp:TextBox ID="txtRandomCode" runat="server"></asp:TextBox>
                    <asp:Button ID="btnGenerate0" runat="server" OnClick="GenerateOTP" Text="Generate" />
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    <asp:TextBox ID="txtTechnology" runat="server" Visible="False"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnAdd" runat="server" Text="Submit" 
                        OnClick="btnAdd_Click" Width="150px" />
                    &nbsp; <asp:Button ID="btnClear" runat="server" Text="Clear" 
                        onclick="btnClear_Click" Width="150px" />
                </td>
            </tr>
        </table>
    </div>
    <br />
    <br />
    <div>
        <table>
            <tr>
                <td>
                    <h2>
                        XML Records</h2>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:GridView ID="grdxml" runat="server" AutoGenerateColumns="false" BackColor="White"
                        BorderColor="Black" BorderStyle="None" BorderWidth="1px" CellPadding="1" GridLines="Vertical"
                        OnSelectedIndexChanged="grdxml_SelectedIndexChanged" 
                        onrowdeleting="grdxml_RowDeleting">
                        <AlternatingRowStyle BackColor="#DCDCDC" />
                        <Columns>
                            <asp:TemplateField HeaderText="ID">
                                <ItemTemplate>
                                    <asp:Label ID="lblEmpId" runat="server" Text='<%# Bind("ID")%>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Name">
                                <ItemTemplate>
                                    <asp:Label ID="lblEmpName" runat="server" Text='<%# Bind("Name")%>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="na">
                                <ItemTemplate>
                                    <asp:Label ID="lblEmpDesignation" runat="server" Text='<%# Bind("Designation")%>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="CourseID">
                                <ItemTemplate>
                                    <asp:Label ID="lblEmpEmailID" runat="server" Text='<%# Bind("EmailID")%>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Description">
                                <ItemTemplate>
                                    <asp:Label ID="lblEmpCity" runat="server" Text='<%# Bind("City")%>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Code">
                                <ItemTemplate>
                                    <asp:Label ID="lblEmpCountry" runat="server" Text='<%# Bind("Country")%>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="na">
                                <ItemTemplate>
                                    <asp:Label ID="lblEmpTechnology" runat="server" Text='<%# Bind("Technology")%>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField>
                                <ItemTemplate>
                                    <asp:LinkButton Text="Select" ID="lnkSelect" runat="server" CommandName="Select" />
                                     <asp:LinkButton ID="lnkDelete" runat="server" CommandName="delete">Delete</asp:LinkButton>
                                </ItemTemplate>
                            </asp:TemplateField>


                        </Columns>
                        <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
                        <HeaderStyle BackColor="Azure" Font-Bold="True" />
                        <PagerStyle BackColor="ActiveCaption" ForeColor="Black" HorizontalAlign="Center" />
                        <RowStyle BackColor="LightCyan" ForeColor="Black" />
                        <SelectedRowStyle BackColor="LightSalmon" Font-Bold="True" ForeColor="White" />
                        <SortedAscendingCellStyle BackColor="#F1F1F1" />
                        <SortedAscendingHeaderStyle BackColor="#0000A9" />
                        <SortedDescendingCellStyle BackColor="#CAC9C9" />
                        <SortedDescendingHeaderStyle BackColor="#000065" />
                    </asp:GridView>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Xml;

namespace xmlInsertUpdateDelete
{
    public partial class XMLAddUpdateDelete : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindGrid();
            }
        }

        private void BindGrid()
        {
            DataSet ds = new DataSet();

            ds.ReadXml(Server.MapPath("~/Courses.xml"));

            if (ds != null && ds.HasChanges())
            {

                grdxml.DataSource = ds;

                grdxml.DataBind();

            }
            else
            {

                grdxml.DataBind();

            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (btnAdd.Text.ToString().Equals("Update Record"))
            {
                DataSet ds = new DataSet();

                ds.ReadXml(Server.MapPath("~/Courses.xml"));

                int xmlRow = Convert.ToInt32(Convert.ToString(ViewState["gridrow"]));

                ds.Tables[0].Rows[xmlRow]["Name"] = txtName.Text;
                ds.Tables[0].Rows[xmlRow]["Designation"] = txtDesignation.Text;
                ds.Tables[0].Rows[xmlRow]["EmailID"] = txtEmailID.Text;
                ds.Tables[0].Rows[xmlRow]["City"] = txtCity.Text;
                ds.Tables[0].Rows[xmlRow]["Country"] = txtRandomCode.Text;
                ds.Tables[0].Rows[xmlRow]["Technology"] = txtTechnology.Text;
                ds.WriteXml(Server.MapPath("~/Courses.xml"));
                BindGrid();

            }
            else
            {
                XmlDocument xmlEmloyeeDoc = new XmlDocument();
                xmlEmloyeeDoc.Load(Server.MapPath("~/Courses.xml"));
                XmlElement ParentElement = xmlEmloyeeDoc.CreateElement("Course");
                XmlElement ID = xmlEmloyeeDoc.CreateElement("ID");
                ID.InnerText = txtID.Text;
                XmlElement Name = xmlEmloyeeDoc.CreateElement("Name");
                Name.InnerText = txtName.Text;
                XmlElement Designation = xmlEmloyeeDoc.CreateElement("Designation");
                Designation.InnerText = txtDesignation.Text;
                XmlElement EmailID = xmlEmloyeeDoc.CreateElement("EmailID");
                EmailID.InnerText = txtEmailID.Text;
                XmlElement City = xmlEmloyeeDoc.CreateElement("City");
                City.InnerText = txtCity.Text;
                XmlElement Country = xmlEmloyeeDoc.CreateElement("Country");
                Country.InnerText = txtRandomCode.Text;
                XmlElement Technology = xmlEmloyeeDoc.CreateElement("Technology");

                Technology.InnerText = txtTechnology.Text;
                ParentElement.AppendChild(ID);
                ParentElement.AppendChild(Name);
                ParentElement.AppendChild(Designation);
                ParentElement.AppendChild(EmailID);
                ParentElement.AppendChild(City);
                ParentElement.AppendChild(Country);
                ParentElement.AppendChild(Technology);
                xmlEmloyeeDoc.DocumentElement.AppendChild(ParentElement);
                xmlEmloyeeDoc.Save(Server.MapPath("~/Courses.xml"));
                BindGrid();
            }
            ClearControl();
        }

        private void ClearControl()
        {
            txtID.Text = string.Empty;
            txtName.Text = string.Empty;
            txtDesignation.Text = string.Empty;
            txtEmailID.Text = string.Empty;
            txtCity.Text = string.Empty;
            txtRandomCode.Text = string.Empty;
            txtTechnology.Text = string.Empty;
            txtID.Enabled = true;
        }

        protected void grdxml_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridViewRow row = grdxml.SelectedRow;
            txtID.Text = (row.FindControl("lblEmpId") as Label).Text;
            txtName.Text = (row.FindControl("lblEmpName") as Label).Text;
            txtDesignation.Text = (row.FindControl("lblEmpDesignation") as Label).Text;
            txtEmailID.Text = (row.FindControl("lblEmpEmailID") as Label).Text;
            txtCity.Text = (row.FindControl("lblEmpCity") as Label).Text;
            txtRandomCode.Text = (row.FindControl("lblEmpCountry") as Label).Text;
            txtTechnology.Text = (row.FindControl("lblEmpTechnology") as Label).Text;
            ViewState["gridrow"] = row.RowIndex.ToString();
            btnAdd.Text = "Update Record";
            txtID.Enabled = false;



        }

        protected void grdxml_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(Server.MapPath("~/Courses.xml"));
            ds.Tables[0].Rows.RemoveAt(e.RowIndex);
            ds.WriteXml(Server.MapPath("~/Courses.xml"));
            BindGrid();
        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            ClearControl();

        }

        protected void Button1_Click(object sender, EventArgs e)
        {

        }

        protected void GenerateOTP(object sender, EventArgs e)
        {

            {
                //string alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                //string small_alphabets = "abcdefghijklmnopqrstuvwxyz";
                string numbers = "1234567890";

                string characters = numbers;
                //if (rbType.SelectedItem.Value == "1")
                //{
                //characters += alphabets + small_alphabets + numbers;
                //characters += numbers;
                //}
                //int length = int.Parse(ddlLength.SelectedItem.Value);
                int length = 5;
                string otp = string.Empty;
                for (int i = 0; i < length; i++)
                {
                    string character = string.Empty;
                    do
                    {
                        //int index = new Random().Next(0, characters.Length);
                        int index = new Random().Next(0, 5);
                        character = characters.ToCharArray()[index].ToString();
                    } while (otp.IndexOf(character) != -1);
                    otp += character;
                }
                //lblOTP.Text = otp;
                txtRandomCode.Text = otp;
            }
        }
    }
}

Upvotes: 0

Views: 638

Answers (1)

user6911980
user6911980

Reputation:

Since the generation of the page is done server-side before it is displayed to the user regarding the ASP side of things (disregarding any AJAX that is triggered and posted to the page that may be called client-side) you can just provide these instructions in the Page Load method.

If you look at the life cycle

You can see that it would be acceptable for your purpose to initialise the control and set properties such as text in the Page Load method for when the page is created. All you need is for runat="server" to be implied and to access the control from the code behind using it's ID. You can then set its innerHTML to whatever you like or it's .Text property or Value.

The assignment will look something like this:

//Front-end:
<input id="txt" runat="Server" type="text" />

//Code behind:
protected void Page_Load(object sender, EventArgs e)
{
    txt.Value = "Bob123";
}

Or this if it's an ASP control:

//In the .aspx:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>



//In the .aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
    TextBox1.Text = SomeMethod();
}

public string SomeMethod()
{
    return "Foo";
}

Upvotes: 1

Related Questions