Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3605
  • Last Modified:

ASP.Net/C# - Datagrid Textbox controls - want to set focus to first control

Hello all.  On my page load after the page rendes I have a datagrid that has rows going across with 4 textbox columns.  I want to set focus to the first control in the 1st datagrid row.  How can I do this after the page loads?  Thanks all
0
sbornstein2
Asked:
sbornstein2
  • 2
1 Solution
 
Darth_helgeCommented:
you can reach controls inside your datagrid like this:
foreach(DataGridItem dgi in myDataGrid.Items)
{

TextBox myTextBox = (TextBox) (dgi.Cells[0].Controls[1]);

ListBox myListBox = (ListBox) (dgi.Cells[1].Controls[1]);

DropDownList myList = (DropDownList) (dgi.Cells[2].Controls[1]);

CheckBox myCheckBox = (CheckBox) (dgi.Cells[3].Controls[1]);

str.Append(myTextBox.Text);

string a = myListBox.SelectedValue;

if(a != null && a != "")

{

str.Append(myListBox.SelectedItem.Text);

}



str.Append(myList.SelectedItem.Text);

str.Append(myCheckBox.Checked);



}

then you can find the right control/textbox you want to focus and then execute this method:
SetFocus(MyControlToFocus)

this is the method:
public static void SetFocus(Control control)
{
    StringBuilder sb = new StringBuilder();
 
    sb.Append("\r\n<script language='JavaScript'>\r\n");
    sb.Append("<!--\r\n");
    sb.Append("function SetFocus()\r\n");
    sb.Append("{\r\n");
    sb.Append("\tdocument.");
 
    Control p = control.Parent;
    while (!(p is System.Web.UI.HtmlControls.HtmlForm)) p = p.Parent;
 
    sb.Append(p.ClientID);
    sb.Append("['");
    sb.Append(control.UniqueID);
    sb.Append("'].focus();\r\n");
    sb.Append("}\r\n");
    sb.Append("window.onload = SetFocus;\r\n");
    sb.Append("// -->\r\n");
    sb.Append("</script>");
 
    control.Page.RegisterClientScriptBlock("SetFocus", sb.ToString());
}
0
 
sbornstein2Author Commented:
yes I am getting the textbox control in actually my itemdatabound can I just do it there but I guess I dont want it to do it for each row everytime
0
 
sbornstein2Author Commented:
thats perfect I have it now.  One more question is there a way not only the focus goes into the box but there are default 0's in the box can I highlight the whole entry in the box if that makes sense?  I am now in my itemdatabound just saying:

      //Set Focus to first Textbox Column
                        if(e.Item.ItemIndex == 0)
                              SetFocus(tb1);
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now