lisbox1.selected index changed to -1 autometically - asp.net

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

Related

method of populate dropdownlist inside gridview

If i want to populate a DropdownList in a GridView what will be the best way? use GridView 'OnRowDataBound' event and fetch query everytime to db or get all data first and put it on datatable and do further work from this datatable ?
As your question is unclear about your requirement, I assume that you want to bind dropdownlist inside the Gridview using OnRowDataBound event of gridview.
So here are the steps:-
Add a Gridview HTML in your aspx page with DropDownList in ItemTemplate of TemplateField.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
<Columns>
<asp:BoundField HeaderText="Name" DataField="ContactName" />
<asp:TemplateField HeaderText = "Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>' Visible = "false" />
<asp:DropDownList ID="ddlCountries" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then you need to bind the gridview with records which will come from the database.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData("SELECT ContactName, Country FROM Customers");
GridView1.DataBind();
}
}
private DataSet GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
Then the code for OnRowDataBound will follow like below :-
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlCountries = (e.Row.FindControl("ddlCountries") as DropDownList);
ddlCountries.DataSource = GetData("SELECT DISTINCT Country FROM Customers");
ddlCountries.DataTextField = "Country";
ddlCountries.DataValueField = "Country";
ddlCountries.DataBind();
//Add Default Item in the DropDownList
ddlCountries.Items.Insert(0, new ListItem("Please select"));
//Select the Country of Customer in DropDownList
string country = (e.Row.FindControl("lblCountry") as Label).Text;
ddlCountries.Items.FindByValue(country).Selected = true;
}
}
See the Reference link for your reference
Also see the Working demo for your reference
Hope that helps.

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

asp.net dropdownlist in gridview

im working on an asp.net website with a gridview.
The gridview has data from an sql database.
Like:
Cuntry----Name
USA--------John
England----Frank
...
The data is loaded in to the gridview like this:
SqlCommand cmd;
cmd = new SqlCommand();
cmd.Connection = sqlConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_loadData";
sqlConn.Open();
dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
So, in the name column, i want a dropdownlist. And I want the dropdownlist with the corresponding value from the database selected.
How can I do this?
Thanks
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:DropDownList Width="50" runat="server" id="ddlCountry" AutoPostBack="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
In Code-behind
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Checking whether the Row is Data Row
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Finding the Dropdown control.
Control ctrl = e.Row.FindControl("ddlCountry");
if (ctrl != null)
{
DropDownList dd = ctrl as DropDownList;
//Here Bind with country list
dd.DataSource = lst;
//Put here the object properties name
dd.DataValueField = "idCountry";
dd.DataTextField = "nameCountry";
dd.DataBind();
//Here add the code to select the current user country in the list
int idUserCountry = 10;
dd.Items.FindByValue(idUserCountry).Selected = true;
}
}
}

SelectedIndex auto select on page load

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);
}

How do I disable the select button text in a gridview after clicking it once? (ASP.NET)

as the title says, How do I disable the select button text in a gridview after clicking it once? I want to click it once, then have the select cell area render an image (and the image not clickable or linking to anything).
Any ideas?
protected void Page_Load(object sender, EventArgs e)
{
dn = new holdDataContext();
if (!(Page.IsPostBack))
{
// GridView1.DataSource = dn.tennis.ToList();
// GridView1.DataBind();
GridView1.DataSource = from c in dn.tennis
orderby c.ID descending
select c;
GridView1.DataBind();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = null;
if (Session["oro"] == null)
{
ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Name"));
dt.Columns.Add(new DataColumn("Description"));
ds.Tables.Add(dt);
Session["oro"] = ds;
}
else
{
ds = (DataSet)Session["oro"];
}
DataRow row = ds.Tables[0].NewRow();
row["Name"] = GridView1.Rows[GridView1.SelectedIndex].Cells[2].Text;
row["Description"] = GridView1.Rows[GridView1.SelectedIndex].Cells[3].Text;
ds.Tables[0].Rows.Add(row);
}
you'll need a combination of aspx markup and code-behind:
aspx:
<asp:GridView ID="gvSample" runat="server"
DataKeyNames="CustomerID"
onselectedindexchanged="gvSample_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnSelect" runat="server" CommandName="Select" Text="Select"></asp:LinkButton>
<asp:Image ID="imgSelect" runat="server" ImageUrl="~/imgs/whatever.jpg" Visible="false" />
</ItemTemplate>
code-behind:
protected void gvSample_SelectedIndexChanged(object sender, EventArgs e) {
LinkButton linkButton = gvSample.SelectedRow.Cells[0].FindControl("btnSelect") as LinkButton;
Image imgWhatever = gvSample.SelectedRow.Cells[0].FindControl("imgSelect") as Image;
linkButton.Enabled = false;
linkButton.Visible = false;
imgWhatever.Visible = true;
}
so, in the ItemTemplate markup of the GridView, specify the image you want to replace the Select button with but make it invisible, then disable the Select button in place of the image by swapping visibility between both objects within the event handler method gvSample_SelectedIndexChanged in the code-behind, which is what gets triggered upon clicking Select button. Since FindControl returns objects of type Control you'll have to cast to the LinkButton type of your Select button.

Resources