Here is my c#:
protected void btnsearch_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection(); {
SqlCommand com = new SqlCommand("sp_studentresult", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", textstudentid.Text);
com.Parameters.AddWithValue("#id_student", textstudentid.Text.Trim());
SqlParameter retval = new SqlParameter("#output", SqlDbType.VarChar, 50);
retval.Direction = ParameterDirection.Output;
com.Parameters.Add(retval);
com.ExecuteNonQuery();
string Output = retval.Value.ToString();
output.Text = Output;
SqlDataAdapter adp = new SqlDataAdapter(com);
DataSet ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
txtid.Text = ds.Tables[0].Rows[0]["id"].ToString();
txttamil.Text = ds.Tables[0].Rows[0]["Tamil"].ToString();
txtenglish.Text = ds.Tables[0].Rows[0]["English"].ToString();
txtmaths.Text = ds.Tables[0].Rows[0]["Maths"].ToString();
txtscience.Text = ds.Tables[0].Rows[0]["Science"].ToString();
txtsocialscience.Text = ds.Tables[0].Rows[0]["SocialScience"].ToString();
}
}
http://s8.postimg.org/n2unbqufp/untitled.jpg <== output screenshot
And here is my aspx:
<table style="width: 60%;" align="center">
<tr>
<td>
<asp:Label ID="output" runat="server" Text=""></asp:Label>
</td>
</tr>
<tr>
<th>Subject Title</th>
<th>Marks</th></tr>
<tr>
<td><asp:Label ID="lblt" runat="server" Text="Tamil"></asp:Label></td>
<td><asp:TextBox ID="txttamil" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="lble" runat="server" Text="English"></asp:Label></td>
<td><asp:TextBox ID="txtenglish" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="lblm" runat="server" Text="Maths"></asp:Label></td>
<td><asp:TextBox ID="txtmaths" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="lbls" runat="server" Text="Science"></asp:Label></td>
<td><asp:TextBox ID="txtscience" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="lblss" runat="server" Text="socialscience"></asp:Label></td>
<td><asp:TextBox ID="txtsocialscience" runat="server"></asp:TextBox></td>
</tr>
<tr><td>
<asp:Button ID="searchupdate" runat="server" Text="Update" OnClick="searchupdate_Click" OnClientClick="return update();" /></td>
</tr>
</table>
Finally storedprocedure:
ALTER PROCEDURE sp_studentresult
(
#id int,
#output varchar(50) output,
#id_student varchar(50)
)
AS
IF NOT EXISTS (SELECT * FROM student WHERE id=#id_student)
BEGIN
SET #output='Doesn not EXIST'
END
SELECT * from studentresult where id_student=#id
I have added search box above the table.. when i enter invalid id, and hit search, below displayed textboxes need to be hide. If i enter valid id and search then only it shows textboxes which are used for update and delete.
May i how to do that? I'm new to .net.
Can anyone guide me?
Related
What I have and doing at the moment:
When the webpage loads the user is presented with form fields to type in some information
then the user has the option the add more fields and add more information.
Then once the user is done they can click on the save button and then it will save the information to my database.
This is the code I have at the moment:
aspx
<script type="text/javascript">
function ExtractData() {
var strValue = GetString();
alert(strValue);
if (strValue != "ERROR") {
E("<%=hdnData.ClientID %>").value = strValue;
return true;
} else {
return false;
}
}
function GetString() {
return "Item:" + E("item1").value + ";Quantity:" + E("qty1").value + ";Cost:" + E("cost1").value + ";Price:" + E("price1").value;
}
function E(id) {
return document.getElementById(id);
}
</script>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
<script type="text/javascript">
function sum() {
var val1 = document.getElementById('TextBox4').value;
var val2 = document.getElementById('TextBox5').value;
var sum = Number(val1) + Number(val2);
document.getElementById('TextBox6').value = sum;
}
</script>
<div class="container-fluid">
<table id="dataTable" width="350px" border="1" style="border-collapse: collapse;">
<tr>
<th>Select</th>
<th>Item Number</th>
<th>Description</th>
<th>Qty</th>
<th>Rate</th>
<th formula="cost*qty" summary="sum">Price</th>
</tr>
<tr>
<td>
<input type="checkbox" name="chk[]" /></td>
<td>1 </td>
<td>
<input type="text" id="item1" name="item[]" />
</td>
<td>
<input type="text" id="qty1" name="qty[]" />
</td>
<td>
<input type="text" id="cost1" name="cost[]" />
</td>
<td>
<input type="text" id="price1" name="price[]" />
</td>
</tr>
</table>
<br />
<input type="button" class="btn-warning" value="Add Row" onclick="addRow('dataTable')" />
<input type="button" class="btn-danger" value="Delete Row" onclick="deleteRow('dataTable')" />
<input type="button" class="btn-info" value="Total" onclick="totalIt()" />
<asp:ImageButton ID="submitButton" runat="server" src="images/send.gif"
OnClientClick="return ExtractData();" OnClick="saveQuote_Click" /><br />
<asp:HiddenField ID="hdnData" Value="" runat="server" />
<asp:Label ID="message" runat="server" />
</div>
aspx.cs
string connStr = #"connection string to database";
protected void saveQuote_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr);
try
{
conn.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(#"INSERT INTO tbl_newQuotes(Item,Description,Rate,Quantity,Price) values(#Item,#Description,#Rate,#Quantity,#Price)", conn);
cmd.Parameters.AddWithValue("#Item", GetStr("Item"));
cmd.Parameters.AddWithValue("#Description", GetStr("Item"));
cmd.Parameters.AddWithValue("#Rate", GetStr("Quantity"));
cmd.Parameters.AddWithValue("#Quantity", GetStr("Cost"));
cmd.Parameters.AddWithValue("#Price", GetStr("Price"));
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
private string GetStr(string title)
{
string[] mystr = hdnData.Value.Split(";".ToCharArray());
string value = string.Empty;
foreach (string Str in mystr)
{
string[] namePair = Str.Split(":".ToCharArray());
if (namePair[0] == title)
{
value = namePair[1];
break;
}
}
return value;
}
The Problem I am facing
So as you can see the above code reads the input values by using jscript and extracting it then saves to the database. All of this works well, but when the users adds more field the that data is not saved only the first field does.
I need to get it to save every row of input fields added to the database.
Any help will be appreciated.
Thanks
To update grids or repeating data? You don't hard code this, you use one of MANY data aware and data repeating controls.
I like listview over grid view. I used the wizards to generate this, deleted all the templates and now have this markup:
<form id="form1" runat="server">
<div>
<link href="Content/cuscosky.css" rel="stylesheet" />
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" >
<EmptyDataTemplate>
<table runat="server" style="">
<tr>
<td>No data was returned.</td>
</tr>
</table>
</EmptyDataTemplate>
<ItemTemplate>
<tr id="myTable1" style="">
<td><asp:Label ID="IDLabel1" runat="server" Text='<%# Eval("ID") %>' /></td>
<td><asp:TextBox ID="DescriptionTextBox" runat="server" Text='<%# Eval("Description") %>' /></td>
<td><asp:TextBox ID="tQty" runat="server" Text='<%# Eval("Qty") %>' style="width:40px"
onchange="updatecost(this.id,'tQty');" />
</td>
<td>
<asp:TextBox ID="tUnitPrice" runat="server" Text='<%# Eval("UnitPrice") %>' style="width:70px;text-align:right"
onchange="updatecost(this.id,'tUnitPrice');"/>
</td>
<td><asp:TextBox ID="tCost" runat="server" Text='<%# Eval("Qty") * Eval("UnitPrice") %>' style="width:70px;text-align:right" /></td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" border="0" >
<tr runat="server" style="">
<th runat="server">ID</th>
<th runat="server">Description</th>
<th runat="server">Qty</th>
<th runat="server">UnitPrice</th>
<th runat="server">Cost</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>
<script>
function updatecost(p, ctl) {
var Qty = $('#' + p.replace(ctl, "tQty"));
var UPric = $('#' + p.replace(ctl, "tUnitPrice"));
var Cost = $('#' + p.replace(ctl, "tCost"));
Cost.val(Qty.val() * UPric.val());
}
</script>
</div>
</form>
As you can see, we don't have a lot of markup.
Now, to load up this grid in code? I have this code:
public class LvInvoiceEDit : System.Web.UI.Page
{
private DataTable rstTable = new DataTable();
protected void Page_Load(object sender, System.EventArgs e)
{
if (System.Web.UI.Page.IsPostBack == false)
{
LoadGrid();
System.Web.UI.Page.Session["rstTable"] = rstTable;
}
else
rstTable = System.Web.UI.Page.Session["rstTable"];
}
public void LoadGrid()
{
string strSQL = "";
strSQL = "SELECT ID, Description, Qty, UnitPrice, Cost FROM InvoiceDetails";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, new SqlConnection(My.Settings.Test3)))
{
cmdSQL.Connection.Open();
rstTable.Load(cmdSQL.ExecuteReader);
ListView1.DataSource = rstTable;
ListView1.DataBind();
}
}
}
Not a lot of code so far, right? Well, we now have this grid:
Now I did play with some JavaScript to update the qty - I think I'll leave that for another day - but it does update quite nice.
So the NEXT big question then is HOW do I save the edit changes back to the data base?
Well, assuming we drop a save button below? Then this code will work:
protected void Button1_Click(object sender, EventArgs e)
{
// save all edits in the grid back to the table:
foreach (ListViewDataItem gvRow in ListView1.Items)
{
int ix = gvRow.DataItemIndex;
{
var withBlock = rstTable.Rows(gvRow.DataItemIndex);
withBlock.Item("Description") = gvRow.FindControl("DescriptionTextBox") as TextBox.Text;
withBlock.Item("Qty") = gvRow.FindControl("tQty") as TextBox.Text;
withBlock.Item("UnitPrice") = gvRow.FindControl("tUnitPrice") as TextBox.Text;
withBlock.Item("Cost") = gvRow.FindControl("tCost") as TextBox.Text;
}
}
// ok, grid is back to the table. Now send table back to database.
using (SqlCommand cmdSQL = new SqlCommand("SELECT ID, Description, Qty, UnitPrice, Cost FROM InvoiceDetails where id = 0",
new SqlConnection(My.Settings.Test3)))
{
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder cmdUpdate = new SqlCommandBuilder(da);
da.Update(rstTable);
}
}
So a few things:
See any mess or truckload of parameters in above? (no!).
Does it matter if we have 3 rows or 30 rows to update? (no!).
Did we really need to write any JavaScript? (no!).
So for bonus points, we probably in the save button should update the total box on the form.
Also, if you not doing a grid? Then I would tag your controls, write a loop to grab the controls into the table. And another routine to take a row and fill the controls. Once you write that routine? ( a fwriter, and rreader to pull or push one data row out to the controls?). Then you can use that fwriter/fread routine to update 5 or 50 controls on a form - and it will only take 2-3 lines of code to udpate those 3 or 40 controls on the form. So be it a grid (repeating rows), or that of just a bunch of controls on the form? You don't need to write and setup a gazillion things (don't need parameters - don't matter if 5 or 40 controls). And in the case of a table like layout (listview), it don't matter if we have 3 or 20 rows of data - its the SAME amount of code and work. This is how things were done on desktop - and the same applies to the web - you don't write code to inject repeating data (well, unless you say using PHP or some such). In asp.net land? We use data repeaters - and save world poverty in terms of the amount of code you do NOT have to write!
And like any desktop software for repeating data? you build the grid - fill it with data. You don't re-add controls on the form manually unless you looking to really make a huge amount of work when none is required.
So, the only trick/issue left? We need a add row button. I'll come back later today and post a few lines for that.
Edit:
code to add a row? Drop a button below the grid, and thus the code is this to add a new row:
protected void Button2_Click(object sender, EventArgs e)
{
// add a new row to the table.
{
var MyNewRow = rstTable.Rows.Add;
MyNewRow.Item("Description") = "new row";
MyNewRow.Item("Qty") = 1;
MyNewRow.Item("UnitPrice") = 0;
MyNewRow.Item("Cost") = 0;
}
// display this new row to the grid
ListView1.DataSource = rstTable;
ListView1.DataBind();
}
Here is the c# file code in which i want to get radio button to every out put so that i can chosen option as we do in "mcqs".
public HtmlString questions_sec1()
{
int userid = Convert.ToInt32(Session["USERID"]);
List<DAO_getQuestiones> get_question_sec1 = new List<DAO_getQuestiones>(DAO_getQuestiones.get_question_sec1(userid)); // data to fech first section
string content = "";
HtmlString theEnvelopePlease = null;
try
{
foreach (var obj in get_question_sec1)
{
content = content + "<tr><td> " + obj.get_question_id + "</td> <td>" + obj.get_answer_question + "</td><td>"+ <input type="radio" name="d" value="data"> DATA +"</td></tr>";
}
theEnvelopePlease = new HtmlString(content);
return theEnvelopePlease;
}
catch (Exception ex)
{
content = content + ex;
theEnvelopePlease = new HtmlString(content);
return theEnvelopePlease;
}
}
Here is the code of html call which is returning the function of cs file for rendering:
<table>
<thead>
<tr>
<th>Sr.</th>
<th>Questions</th>
<th>Answers</th>
</tr>
</thead>
<tbody>
< %:questions_sec1() % >
</tbody>
</table>
Question: I want the radio button to every out put of answer so that i can chose one option and one more thing.
It is difficult to add form element with HTML string into ASP.NET form.
Instead, I suggest you to use a 'Repeater':
<asp:Repeater id="Repeater1" runat="server">
<HeaderTemplate>
<table>
<thead>
<tr>
<th>Sr.</th>
<th>Questions</th>
<th>Answers</th>
</tr>
</thead>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td> <%#Eval("get_question_id ") %> </td>
<td> <%#Eval("get_answer_question ") %> </td>
<td> <asp:RadioButton ID="RadioButton" runat="Server" Text="DATA" /> </td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
And in your .cs file, bind the data to the Repeater like this:
Repeater1.DataSource = get_question_sec1;
Repeater1.DataBind();
Here is the MSDN link of Repeater: https://msdn.microsoft.com/en-US/library/system.web.ui.webcontrols.repeater.itemtemplate(v=vs.110).aspx
Thanks for your responce but i dn't want to you built in control from the tool box of asp.net.
I need to generate excel report based on the dates selected. Every things works fine but my excel sheet is not generating but its working fine when i try to export in web forms. But if i use master page and content page its not working..
here is my code
aspx
<center>
<table>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Start Date:" style="color:white"></asp:Label>
</td>
<td>
<asp:TextBox ID="datepicker" runat="server"></asp:TextBox>
</td>
<td>
<img src="../Images/calendar.gif" id ="datepic"/>
<cc1:calendarextender ID="ceFromDate" runat="server" TargetControlID="datepicker"
Format="dd-MMM-yyyy" Enabled="True" PopupButtonID="datepic" CssClass="black">
</cc1:calendarextender>
</td>
</tr>
<br />
<br />
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text="End Date:" style="color:white"></asp:Label>
</td>
<td>
<asp:TextBox ID="datepicker1" runat="server"></asp:TextBox>
</td>
<td>
<img src="../Images/calendar.gif" id="datepic1" />
<cc1:calendarextender ID="Calendarextender1" runat="server" TargetControlID="datepicker1"
Format="dd-MMM-yyyy" Enabled="True" PopupButtonID="datepic1" CssClass="black">
</cc1:calendarextender>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="Get Report" OnClick="Button1_Click" />
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" ></asp:GridView>
</center>
cs code:
protected void Button1_Click(object sender, EventArgs e)
{
using (OracleConnection con = new OracleConnection(constr))
{
//for getting id
con.Open();
OracleCommand cmd = new OracleCommand("select adcomplain_no as \"AD COMPLAIN NO\",to_char( COMPLAINT_DATE,'DD/MM/YY') as \"COMPLAINT DATE\",nature_of_complaint as \"NATURE OF COMPLAINT\",(select categoryname from crs_categorynew where crsid=complaint_categoryID)as \"CATEGORY NAME\",(SELECT subcategoryname FROM CRS_SUDCATEGORYNEW WHERE CRSSUBID=complaint_subcategory) as \"SUB CATEGORY NAME\",seat_location AS \"SEAT LOCATION\",seatno AS \"SEAT NO\",extensionno AS \"EXTENSION NO\",to_char(entry_date,'DD/MM/YY')as \"ENTRY DATE\" ,(select staffno||'-'||NAME as name from employee where staffno=entry_by) as \"ENTRY BY\" ,(CASE STATUSFLAG WHEN 'U' THEN 'Un Allotted' WHEN 'AN' THEN 'Allotted' WHEN 'B' THEN 'Being Completed' WHEN 'C' THEN 'Completed' WHEN 'UA' THEN 'Un Attented' ELSE '' END)as \"STATUS\",(select staffno||'-'||NAME as name from employee where staffno=alloted_person) as \"ALLOTED PERSON\",to_char(target_date,'DD/MM/YY') as \"TARGET DATE\",(select staffno||'-'||NAME as name from employee where staffno=alloted_by) as \"ALLOTED BY\",to_char(alloted_date,'DD/MM/YY') as \" ALLOTED DATE\",complain_reason as SOLUTION,to_char(complain_statusdate, 'DD/MM/YY')as \"COMPLAIN STATUS DATE\",(select staffno||'-'||NAME as name from employee where staffno=complain_statusby)AS \"COMPLAIN STATUS BY\" from crs_complaint where complaint_date between (TO_DATE('" + datepicker.Text + "', 'dd/mm/yyyy')) and (TO_DATE('" + datepicker1.Text + "', 'dd/mm/yyyy'))", con);
OracleDataAdapter oda = new OracleDataAdapter(cmd);
DataTable dt = new DataTable();
oda.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
string headerTable = #"<h1>Service Request List from '" + datepicker.Text + "' to '" + datepicker1.Text + "'</h1>";
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
//Range rg = (Excel.Range)worksheetobject.Cells[1, 1];
//rg.EntireColumn.NumberFormat = "MM/DD/YYYY";
Response.Write(headerTable);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
con.Close();
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
cretae a trigger for the button in updatepanel, this may solve your problem..
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
I have an ASP.Net page with 3 textboxes and 1 radiobuttonlist. Each of the 4 controls has
class="tabbable"
in its definition. Here's the complete markup:
<%# Control Language="c#" AutoEventWireup="false" Codebehind="approvalacctprocess.ascx.cs" Inherits="cmc.workflow.ui.ApprovalAcctProcess" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<%# Register tagprefix="CMC" Tagname="ApprovalComments" src="~/workflow\ui\ApprovalComments.ascx" %>
<script src="../../Scripts/jquery-1.4.1.js"></script>
<asp:Panel ID="pnlApprovalAC" CssClass="STDPANEL" HorizontalAlign="Center" Runat="server" Width="550">
<TABLE cols="2" width="520">
<TR>
<TD class="FLDLABEL" style="VERTICAL-ALIGN: top">Client Number</TD>
<TD>
<asp:TextBox id=txtclnum style="VERTICAL-ALIGN: top" Width="300" Runat="server" CssClass="FLDVALUE" TabIndex="0" onchange="MoveNext(this);" Text='<%# Property["clnum"] %>' MaxLength="14" AutoPostBack="True" class="tabbable"></asp:TextBox>
<asp:RegularExpressionValidator id="rxClNum" ValidationExpression="^[0-9]+[ ]*$|Clt Number TBD" ErrorMessage="Client Number consists of up to 14 numbers"
ControlToValidate="txtclnum" runat="Server"></asp:RegularExpressionValidator></TD>
<TR>
<TD class="FLDLABEL" style="VERTICAL-ALIGN: top">Matter Number (5-6 digit)</TD>
<TD>
<asp:Label id=lbclnum style="TEXT-ALIGN: right" Width="140" Runat="server" Text='<%# Property["clnum"] %>' Font-Name="verdana" Font-Size="x-small">
</asp:Label>-
<asp:TextBox id=txtmmatter Width="150" Runat="server" CssClass="FLDVALUE" TabIndex="1" Text='<%# Property["mmatter"] %>' MaxLength="6" AutoPostBack="True" class="tabbable"></asp:TextBox>
</TD>
<TR>
<TD colSpan="2">
<HR style="COLOR: gray; TEXT-ALIGN: left" SIZE="1">
</TD>
</TR>
<tr>
<td class="FLDLABEL" style="VERTICAL-ALIGN: top" width="500" colspan="2"><asp:Label runat="server" ID="lbExistingClientQuestion" Text="Is there an Engagement Letter on file for this client?" Visible="false" />
<asp:Label runat="server" ID="lbUDFRetainerLetter" Text='<%# Property["RetainerLetter"] %>' Visible="false" /></td>
</tr>
<TR>
<TD class="FLDLABEL" style="VERTICAL-ALIGN: top" width="500" colSpan="2">Has a
retainer/engagement letter been submitted and approved by Charlotte Fischman?</TD>
</TR>
<TR>
<TD colSpan="2">
<asp:RadioButtonList id="rblRetLtrReturned" TabIndex="2" Runat="server" CssClass="RADIOBUTTONLIST" RepeatDirection="Horizontal" class="tabbable"
RepeatLayout="Table" RepeatColumns="1" width="300" AutoPostBack="True">
<asp:ListItem Value="0">No</asp:ListItem>
<asp:ListItem Value="1">Yes</asp:ListItem>
</asp:RadioButtonList>
<asp:Label id="lblnoretainerltrneeded" Runat="server" CssClass="SMALLNOTE" Text="(This is an existing client and the matter is in an existing area of law.
A retainer letter may not be needed.)"
Font-Size="xx-small" Visible="False" ForeColor="red"></asp:Label></TD>
</TR>
<TR>
<TD colSpan="2">
</TD>
</TR>
<TR>
<td class="FLDLABEL" style="VERTICAL-ALIGN: top" colSpan="2" width="500">Reason for Not Submitting an Retainer/Engagement Letter for Approval<SPAN style="FONT-WEIGHT: bold; COLOR: red">
*</SPAN>
<asp:Label runat="server" CssClass="SMALLNOTE" Text="(Required if no retainer letter submitted and not an existing client)" Font-Size="XX-Small" ForeColor="Red" /></td>
</TR>
<TR>
<td colspan="2">
<asp:TextBox Width="500" runat="server" TextMode="MultiLine" TabIndex="3" CssClass="FLDVALUE" ID="txtReason" MaxLength="500" Text='<%# Property["Reason"] %>' AutoPostBack="True" class="tabbable" />
</td>
</TR>
<TR>
<TD colSpan="2">
<HR style="COLOR: gray; TEXT-ALIGN: left" SIZE="1">
</TD>
</TR>
<TR>
<TD class="FLDLABEL" style="VERTICAL-ALIGN: top">Comments</TD>
<TD>
<asp:TextBox id="txtComments" style="VERTICAL-ALIGN: top" Width="300" TabIndex="4" Runat="server" CssClass="FLDVALUE"
MaxLength="450" Rows="5" TextMode="MultiLine" Text='<%# Property["AcctgComment"] %>' AutoPostBack="True" class="tabbable"></asp:TextBox></TD>
</TR>
</TABLE>
<TABLE class="STDPANEL" style="VERTICAL-ALIGN: middle" height="50" width="550">
<TR>
<td align="center">
<input id="btnSaveACProperty" runat="server" name="btnSaveACProperty"
onserverclick="OnSave_Click" type="submit" value="Save Status and Comment">
<input id="btnResetACProperty" runat="server" name="btnResetACProperty"
type="reset" value="Cancel">
</input>
</input>
</td>
<tr>
<td align="left">
<asp:ValidationSummary ID="valsum" runat="server" BorderColor=""
BorderStyle="Solid" BorderWidth="2" CssClass="VALIDATORSUM" DisplayMode="List"
Font-Bold="True" ForeColor="red"
HeaderText=" Some errors occurred in your input. Please correct them:<br> "
ShowMessageBox="True" ShowSummary="True" Width="500" />
</td>
</tr>
</TABLE>
</asp:Panel>
<script type="text/vbscript">
</script>
<script type="text/javascript" lang="javascript">
function MoveNext(ele) {
$(document).ready(function () {
var lastTabIndex = 4;
var currentElementID = ele.id; // ID set by OnFocusIn
var currentElement = document.getElementById(currentElementID);
var curIndex = currentElement.tabIndex; //get current elements tab index
if (curIndex == lastTabIndex) { //if we are on the last tabindex, go back to the beginning
curIndex = 0;
}
var tabbables = document.querySelectorAll("tabbable"); //get all tabbable elements
alert(tabbables.length);
for (var i = 0; i < tabbables.length; i++) { //loop through each element
if (tabbables[i].tabIndex == (curIndex + 1)) { //check the tabindex to see if it's the element we want
tabbables[i].focus(); //if it's the one we want, focus it and exit the loop
break;
}
}
});
}
</script>
The textbox txtclnum calls the javascript function MoveNext at the bottom of the page (just to make sure everything loads in the right order)(this is taken from the first answer to this question). MoveNext has an alert in it to tell me what tabbables.length is. The alert returns 0 because the CssClass in the .Net controls overwrites the class="tabbable" in the HTML. I've tried
var tabbables = document.getElementsByTagName("*");
which gets me to the correct control, but the focus doesn't stay on that control. How can I keep the focus on the control?
That function takes as its argument a CSS selector, so if you're looking for elements with class "tabbable" you would use document.querySelectorAll(".tabbable")
Since tabbable is a class, you need to put a period in front of it in your queryselector, so it should be:
document.querySelectorAll(".tabbable")
Edit: Just further clarification, the queryselector without the "." would be looking for html tags like <tabbable>. Since that does not exist, the length returned is 0.
The way you're using it, document.querySelectorAll("tabbable") is looking for an element of the tag <tabbable>. Since it looks like you're trying to query by a class, add the period to denote it is such.
document.querySelectorAll(".tabbable")
When you use document.getElementsByClassName("tabbable") it could work, so I could see where you could get confused if you've used that method in the past.
OK, I feel like an idiot. Just for others' future reference, the problem was that 1) there's a Cssclass assigned to those controls, which overrides my tabbable class in the HTML markup; and 2) once I took care of that (see below code), it still wasn't working because (duh) each control had an AutoPostBack=true on it (they used to have server-side code attached to them). Now that AutoPostBack is false, my code works fine. Here it is:
<script type="text/javascript" lang="javascript">
function MoveNext(currentElement, btnID) {
$(document).ready(function () {
var saveButton = document.getElementById(btnID);
saveButton.disabled = false;
var lastTabIndex = 4;
var curIndex = currentElement.tabIndex; //get current elements tab index
if (curIndex == lastTabIndex) { //if we are on the last tabindex, go back to the beginning
curIndex = 0;
}
var tabbables = document.getElementsByTagName("*"); //get all tabbable elements
for (var i = 0; i < tabbables.length; i++) { //loop through each element
if (tabbables[i].tabIndex != null & tabbables[i].tabIndex == (curIndex + 1)) { //check the tabindex to see if it's the element we want
tabbables[i].focus(); //if it's the one we want, focus it and exit the loop
break;
}
}
});
}
Thanks to everyone for their help.
I'm having a Drop-down-list and a Text-box with auto-completed extender on my web form.
Now i need to set ContextKey property of auto-completed extender from java-script.
I'm trying to set ContextKey property using java-script on onkeyup event of text-box. But it's not working
.aspx code
<table>
<tr>
<td style="width:100px;">
<asp:Label ID="Label1" CssClass="lbl" runat="server" Text="Server:"></asp:Label>
</td>
<td colspan="4">
<asp:DropDownList ID="DropDownList1" CssClass="Comb" runat="server"
OnSelectedIndexChanged="ddlServer_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label2" CssClass="lbl" runat="server" Text="Originating:"></asp:Label>
</td>
<td colspan="4">
<asp:TextBox runat="server" ID="TextBox1" CssClass="tb10" autocomplete="off" onkeyup="SetContextKey()"/>
<ajaxToolkit:AutoCompleteExtender TargetControlID="TextBox1" UseContextKey="true"
runat="server" BehaviorID="AutoCompleteEx" ID="AutoCompleteExtender1"
ServicePath="AutoComplete.asmx" ServiceMethod="GetResellerList"
MinimumPrefixLength="1" CompletionInterval="1000" EnableCaching="true" FirstRowSelected="true"
CompletionSetCount="20" CompletionListCssClass="cssList" DelimiterCharacters=";, :"
ShowOnlyCurrentWordInCompletionListItem="true" OnClientHiding="OnClientCompleted"
OnClientPopulated="OnClientCompleted" OnClientPopulating="OnClientPopulating">
</ajaxToolkit:AutoCompleteExtender>
</td>
</tr>
</table>
.cs code (Service Code)
[WebMethod]
public string[] GetResellerList(string prefixText, int count, string contextKey)
{
DataSet ds = new DataSet();
ds = clsTransaction.Select("SELECT nm AS Name FROM tblReseller WHERE nm LIKE '" + prefixText + "%' AND wsid = '" + contextKey + "'",
DataSendBSSWEB.ServerDbEnum.MainSqlServer,
false);
//Then return List of string(txtItems) as result
List<string> txtItems = new List<string>();
String dbValues;
foreach (DataRow row in ds.Tables[0].Rows)
{
dbValues = row["Name"].ToString();
txtItems.Add(dbValues);
}
return txtItems.ToArray();
}
javascript Code
<script type="text/javascript">
function SetContextKey() {
$find('<%=autoComplete2.ClientID%>').set_contextKey($get("<%=ddlServer.ClientID %>").value);
}
</script>
Can any one tell me how can i do this using java-script.
Target control id of the extender should be the TextBox's Id, Not the drop down's.