SelectedIndex auto select on page load - asp.net

I have an account page where the user can view their account information.. I want them to be able to change their password here. The Way I have managed to implement it it is as follows:
Web service:
[WebMethod]
public string ChangePassword(DataSet ds)
{
string database = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/dvd_forum.accdb;Persist Security Info=True";
OleDbConnection myConn = new OleDbConnection(database);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from Users", myConn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(myDataAdapter);
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";
myConn.Open();
myDataAdapter.Update(ds, "Users");
myConn.Close();
return "Password changed!";
}
Front code:
<asp:Label ID="username" runat="server" Text=""></asp:Label><span>'s Account</span><br />
<asp:TextBox ID="ChangePasswordInput" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Save"
onclick="ChangePassword_Click" />
<asp:Label ID="Label2" runat="server" Text=""></asp:Label><asp:RequiredFieldValidator id="RequiredFieldValidator3" runat="server" ErrorMessage="Required!" ControlToValidate="ChangePasswordInput"></asp:RequiredFieldValidator>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
back code:
public partial class Account : System.Web.UI.Page
{
public static DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
username.Text = User.Identity.Name;
}
localhost.Service1 myws = new localhost.Service1();
ds = myws.GetUserAcc(User.Identity.Name);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void ChangePassword_Click(object sender, EventArgs e)
{
//change password
int i = GridView1.SelectedIndex;
ds.Tables["Users"].Rows[i]["password"] = ChangePasswordInput.Text;
GridView1.DataSource = ds;
GridView1.DataBind();
localhost.Service1 myws = new localhost.Service1();
Label2.Text = myws.ChangePassword(ds);
}
}
The problem with this is that I have to select the row in the gridview before changing the password. Is there any way I can have the row automatically selected as there will only ever be one row.. Or how can I code it differently to work without selecting the row first?
Thanks.

Your GridView and button are separate controls on the page, therefore you can't determine which user is selected for password change, without selecting the row in the GridView. IMO its better if you could put the button inside the GridView. Make an editable GridView.
Edit: Based on your comment that you will only have one row in your grid view, I really don't see the reason of using Gridview with datatable. You can have a label showing user name and textbox for new password. (You may wanna reconfirm the password). Then in your webservice, instead of passing datatable, you may pass the new password (its better if its encrypted) and then update the data using SQL Update statement. But if you still want to use the GridView then instead of getting the selectedIndex you can directly pass 0 in the Row index. You may check if the dataTable contains any row.
if(ds.Tables.Count > 0 && ds.Tables["Users"] != null && ds.Tables["Users"].Rows.Count > 0)
{
ds.Tables["Users"].Rows[0]["password"] = ChangePasswordInput.Text;
    GridView1.DataSource = ds;
    GridView1.DataBind();
    localhost.Service1 myws = new localhost.Service1();
    Label2.Text = myws.ChangePassword(ds);
}

Related

CheckedItems.Count Always Returns a Value of Zero (0)

I have Use telerik:radcombobox with mutiple select value.I have bind data LoadOndemand.All Work Fine but when i click on submit button then CheckedItems.Count=0.
Thank you,
Dhiren Patel
I believe you are using EnableLoadOnDemand property of the RadComboBox. RadComboBox items are not accessible on the server-side when loading them on demand and therefore always return CheckedItems as well as SelectedItems count as zero and this is a known issue. This is because RadComboBox items loaded on demand using the ItemsRequested event handler or WebService do not exist on the server and cannot be accessed using the server-side FindItemByText / Value methods. SelectedItem and SelectedIndex properties are always Null / Nothing. This is needed for speed (otherwise the combobox will not be that responsive upon each keypress if state information and ViewState were persisted).
Please have a look at the following code without using load on demand which works fine at my end.
<telerik:RadComboBox runat="server" ID="RadComboBox1" CheckBoxes="true">
</telerik:RadComboBox>
<br />
<br />
<telerik:RadButton ID="RadButton1" runat="server" Text="Get Count" OnClick="RadButton1_Click">
</telerik:RadButton>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateRadCombobox("select ContactName from Customers");
}
}
protected void populateRadCombobox(string query)
{
String ConnString =
ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(ConnString);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(query, conn);
DataTable myDataTable = new DataTable();
conn.Open();
try
{
adapter.Fill(myDataTable);
RadComboBox1.DataTextField = "ContactName";
RadComboBox1.DataSource = myDataTable;
RadComboBox1.DataBind();
}
finally
{
conn.Close();
}
}
protected void RadButton1_Click(object sender, EventArgs e)
{
if (RadComboBox1.CheckedItems.Count > 0)
{
//business logic goes here
}
else
{
}
Reference:
http://www.telerik.com/forums/checkeditems-count-always-returns-a-value-of-zero-0
http://www.telerik.com/forums/radcombobox-losing-client-selections-on-postback

How to disable some checkboxes of checkboxlist based on database value in asp.net?

I have a checkboxlist which has 26 values getting filled from database.
<asp:CheckBoxList ID="chkList1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" Width="100%" DataTextField="Name" DataValueField="ID" AutoPostBack="True" Visible="false" OnSelectedIndexChanged="chkList1_SelectedIndexChanged">
</asp:CheckBoxList>
public QueSet()
{
SqlConnection conn = new SqlConnection(Settings.DatabaseConnectionString);
try
{
conn.Open();
SqlCommand com = new SqlCommand("sp_SelectQueSet",conn);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sa = new SqlDataAdapter(com);
DataSet ds = new DataSet();
sa.Fill(ds);
if(ds.Tables.Count > 0)
{this.Data = ds.Tables[0];}
}
catch(Exception ex)
{
throw new ApplicationException(ex.Message);
}
finally
{conn.Close();}
}
QueSet q = new QueSet();
chkList1.DataSource = q.Data;
chkList1.DataBind();
Based on above code, the checkboxlist gets data from database. One of the values from the database is "Nothing" with ID 51.
I want to disable all the other checkboxes if user selects "Nothing" value.
protected void chkList1_SelectedIndexChanged(object sender, EventArgs e)
{
//what should I do here?
}
This can be easly achived by Client Script, Server SelectedIndexChanged is not required. do the steps as follows
Remove AutoPostback = "true" and OnSelectedIndexChanged="..." from
your CheckboxList control and Add the property CssClass ="CHKList"
Attach jQuery.js , say jQuery-1.7 or latest version
Add the following code in ASPX Page. This will disable all checkboxes when anyone of check box is clicked and Enable back if unchecked
<script>
$(document).ready(function () {
$(".CHKList input:checkbox").click(function () {
if ($(this).prop("checked") == true) {
$(".CHKList input:checkbox").prop("disabled", true);//older version of jQuery prop will not work , use attr("disabled","disabled");
$(this).prop("disabled", false);
}
else {
$(".CHKList input:checkbox").prop("disabled", false);
}
});
});
</script>
First set data source to checkboxlist as your are doing
Then try this (Not tested, sorry for that)
for (int i = 0; i < chkList.Items.Count; i++)
{
if (Chkboxlist.Items[i].Value == "SomeValue")
{
Chkboxlist.Items[i].Enabled = false;
}
}

lisbox1.selected index changed to -1 autometically

I have a listbox in asp.net and I am binding list Items from database. I have a button named "submit". Now when pages loads I am getting desired values in listbox, but when I am selecting any value and pressing submit button it sets listbox's selected index to -1.
can anyone help me to get proper index value?
<div class="PageRight">
<asp:ListBox ID="ListOfSql" runat="server" SelectionMode="Single" DataTextField="sql_name"
DataValueField="sql_text" Style="margin-left: 0px" Width="205px" EnableViewState="true"
OnSelectedIndexChanged="ListOfSql_SelectedIndexChanged">
</asp:ListBox><br />
<asp:Button ID="btnPreSqlExe" runat="server" Text="Sumbit"
onclick="btnPreSqlExe_Click">
</asp:Button>
</div>
and .cs page is like
protected void btnPreSqlExe_Click(object sender, EventArgs e)
{
txtQuery.Text = ListOfSql.SelectedItem.Value.ToString();
}
To Bind Data in listBox I am using following Code
Private void loadSqlList()
{
if (!IsPostBack)
{
conn.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
string preSql = "select sql_name, sql_text from cn_sql_log order by sql_name";
OracleDataAdapter da = new OracleDataAdapter(preSql, conn);
da.Fill(ds);
ListOfSql.DataSource = ds;
ListOfSql.DataTextField = "Sql_Name";
ListOfSql.DataValueField = "sql_Text";
ListOfSql.DataBind();
ListOfSql.SelectedIndex = 0;
conn.Close();
}
and calling loadSqlList() on page_load

GridView lost sorting after paging?

I got the below code from internet. It is working properly. I have added paging also. When I'm just sorting, it is working properly. When I am changing the page index, the sorting is lost.
Here is the client side code that set a gridview with 20 items per page, using the sort linked to the "GridView1_Sorting" method in the server side code.
Client side
<asp:GridView ID="GridView1" runat="server" DataKeyNames="eno" AutoGenerateColumns="False" PageSize="20" AllowPaging="True" AllowSorting="True" OnSorting="GridView1_Sorting" CellPadding="4">
<Columns>
<asp:TemplateField HeaderText="Employee no" SortExpression="eno">
<ItemTemplate>
<%#Eval("eno")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp name" SortExpression="empname">
<ItemTemplate>
<%#Eval("empname")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary" SortExpression="sal">
<ItemTemplate>
<%#Eval("sal")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And now the server side code:
Server side
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridData();
}
}
void GridData()
{
sqlcmd = new SqlCommand("select * from emp", sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["dt"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
private string GVSortDirection
{
get { return ViewState["SortDirection"] as string ?? "DESC"; }
set { ViewState["SortDirection"] = value; }
}
private string GetSortDirection()
{
switch (GVSortDirection)
{
case "ASC":
GVSortDirection = "DESC";
break;
//assign new direction as ascending order
case "DESC":
GVSortDirection = "ASC";
break;
}
return GVSortDirection;
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = (DataTable)Session["dt"];
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
string sortDirection = GetSortDirection();
dataView.Sort = e.SortExpression + " " + sortDirection;
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridData();
}
}
When you page, the PageIndexChanging event is called. This in turn runs the GridData() procedure, which sets the data source for the gridview to be a data table containing records from the emp table, with no particular sort order.
What you should do is to take the code that you've written in your GridView1_Sorting event-handler, and include this within the GridData routine, so that whenever the grid is populated with data - whether when the page first loads, when the page index is changed or when the gridview is sorted - the gridview is based on a sorted dataview, rather than an unsorted data table.
The way you are maintaining SortDirection using GetSortDirection, in same fashion maintain SortExpression.
Happy coding!!!
Have a look to this article, may you will get what you want

Search GridView

I have a guestbook at the moment displaying "comment", "comment_time", "user". I want to add a search box below and then search the gridview by "user" and then bind the data to a new grid view below. I am under strict instructions to have all data interactions passed via a web service.
I have a Web Method at the moment to get all the comments:
[WebMethod]
public DataSet SearchDatabase(string query)
{
DataSet ds = new DataSet();
string database = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/dvd_forum.accdb;Persist Security Info=True";
string queryStr = "SELECT * FROM Comments WHERE User LIKE '%query%'";
OleDbConnection myConn = new OleDbConnection(database);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(queryStr, myConn);
myConn.Open();
myDataAdapter.Fill(ds, "Comments");
myConn.Close();
return ds;
}
Here's the front code:
<asp:Label ID="Label3" runat="server" Text="Search"></asp:Label><asp:TextBox ID="TextBoxSearch"
runat="server"></asp:TextBox><asp:Button ID="ButtonSearch"
runat="server" Text="Search" onclick="ButtonSearch_Click" />
<asp:GridView ID="GridView2" runat="server">
The code behind:
protected void ButtonSearch_Click(object sender, EventArgs e)
{
string query = TextBoxSearch.Text;
localhost.Service1 myws = new localhost.Service1();
ds = myws.SearchDatabase(query);
GridView2.DataSource = ds;
GridView2.DataBind();
}
It just doesn't do anything at all, page refreshes with no new GridView or any other action.
On another side note:
I have another input on the same page with a required field validator that doesn't let me search unless I fill the input with some text. How can I resolve this?
Thanks.
string queryStr = "SELECT * FROM Comments WHERE User LIKE '%"+query+"%'";

Resources