How to set the Focus on Newly added record

Posted by Krishnamanohar under .NET Certifications on 10/17/2012 | Points: 10 | Views : 2163 | Status : [Member] | Replies : 1
Hi
I have a gridview .after click on add button New record is Added in the Grid.
But the problem is i want to set the focus on newly added Record.
Please Help me Urgent]

Regards,
Krishna Manohar




Responses

Posted by: Vasanthmvp on: 10/17/2012 [Member] Starter | Points: 25

Up
0
Down
Hi, just include in the submit button of adding a new record. To find the latest added row and add the css style or color changes or anything to make it focused to that particular row.

I am here presenting you a sample code.
Here, i took a sample Table PersonalDetails with FirstName, LastName, Age, Active as columns.

.aspx page:


<form id="form1" runat="server">
<div>
<asp:GridView ID="grid" runat="server" />
FirstName: <asp:TextBox ID="txtfn" runat="server" /> <br />
LastName: <asp:TextBox ID="txtln" runat="server" /> <br />
Age: <asp:TextBox ID="txtage" runat="server" /> <br />
Active: <asp:DropDownList ID="drodown" runat="server">
<asp:ListItem Text="Yes" Value="True" />
<asp:ListItem Text="No" Value="False" />
</asp:DropDownList> <br />
<asp:Button ID="btnsubmit" runat="server" Text="Submit" OnClick="SubmitRecord" />
</div>
</form>


.aspx.cs

  string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;


DataTable table = new DataTable();

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetData();
}
}

private void GetData()
{
int insertedrowindex;
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "Select * from PersonalDetails";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(table);
}
}
}
grid.DataSource = table;
grid.DataBind(); // After binding the data to the gridview, i am finding the latest added row and changing its font color. So, whenever a new record is added, it gets focused.
insertedrowindex = grid.Rows.Count;
grid.Rows[insertedrowindex-1].ForeColor = System.Drawing.Color.Blue;
}

protected void SubmitRecord(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "Insert INTO PersonalDetails(FirstName, LastName, Age, Active) values(@FirstName, @LastName, @Age, @Active)";

using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@FirstName", txtfn.Text);
cmd.Parameters.AddWithValue("@LastName", txtln.Text);
cmd.Parameters.AddWithValue("@Age", txtage.Text);
cmd.Parameters.AddWithValue("@Active", drodown.SelectedValue);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
GetData();
}

Hope this gave you a clear explanation.
Regards,

Awesome Coding !! :)

Krishnamanohar, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response