asp.net dropdownlist first selection does not fire SelectedIndexChanged event - c#

I've created a dropdownlist, and tried clicking on the first selection but there was no firing of the SelectedIndexChanged event. However, it worked perfectly fine for the rest of the options in the dropdownlist.
Here are my codes:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string member = (String)Session["ssmem"];
if (!IsPostBack)
{
if (Session["ssmem"] == null)
Response.Redirect("LoginforAccess.aspx");
else
{
Response.ClearHeaders();
Response.AddHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
Response.AddHeader("Pragma", "no-cache");
//if go back then must log in --2
}
//Dropdownlist
string strConnectionString =
ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
//STEP1 : Define a connection to Database
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strcommand = "Select Username from [User] WHERE (UsergroupID = (SELECT UsergroupID FROM [User] AS User_1 WHERE (Username = #user)))";
SqlCommand cmd = new SqlCommand(strcommand, myConnect);
// cmd.Parameters.AddWithValue("#usergrp", groupid);
cmd.Parameters.AddWithValue("#user", member);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader();
DropDownList1.DataSource = reader;
DropDownList1.DataTextField = "Username";
DropDownList1.DataValueField = "Username";
DropDownList1.DataBind();
reader.Close();
myConnect.Close();
}
}
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if (Session["ssmem"] != null)
MasterPageFile = "User.master";
//change the master page --1
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
//chosen name to display stats
string choseuser = "";
choseuser = DropDownList1.SelectedItem.Text;
Response.Redirect("Substats.aspx?choseuser=" + choseuser);
}
}
Source view for dropdownlist:
<asp:DropDownList ID="DropDownList1" runat="server" Width="200px" Height="35px"
AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged"
ViewStateMode="Enabled">
</asp:DropDownList>

We have to add first item as title to the dropdownlist,
and instead of using datasource used dr.Read() in while loop for adding the items on dropdownlist.
This problem occurs because in dropdownlist first item is selected bydefault and it is not reflected on selection
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" ViewStateMode="Enabled">
<asp:ListItem>Select College</asp:ListItem>
<!--Add one item as title into dropdownlist in edit item of dropdownlist-->
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("hello");
try
{
string sel = "select name from websites";
SqlCommand cmd = new SqlCommand(sel,con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
/* DropDownList1.DataSource = dr;
DropDownList1.DataTextField = "name";
DropDownList1.DataValueField = "name";
DropDownList1.DataBind();*/
while (dr.Read())//used dr.read() instead of datasource
{
DropDownList1.Items.Add(dr["name"].ToString());
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand("select url from websites where name = #itm", con);
cmd.Parameters.AddWithValue("#itm", DropDownList1.SelectedItem.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
Response.Redirect(dr["url"].ToString());
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}

Related

Checkbox OnCheckedChange event with postback?

I have a gridview with checkbox controls as columns and with Autopostback='true' for inserting to db.
Everyting works fine except when i "change pages" - Postback (?)
My checked checkboxes gets unchecked when I go back to the page.
My Page_Load have a !IsPostBack and then i bound my gridview (gwPlanning)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridViewPlanning();
}
}
and my code behind:
protected void myCheckBox_OnCheckedChange(object sender, EventArgs e)
{
CheckBox myCheckBox = (CheckBox)sender;
GridViewRow row = (GridViewRow)myCheckBox.NamingContainer;
string ThisWeekMinus2 = row.Cells[1].Text;
bool status = myCheckBox.Checked;
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("UPDATE [BI_Planning].[dbo].[tblPlanning] SET [This Week - 2] = #IsActive WHERE ActivityID = #ID ", con);
cmd.Parameters.Add("#IsActive", SqlDbType.Bit).Value = myCheckBox.Checked;
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = ThisWeekMinus2;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
any idea what i'm missing?
The solution was just to add:
Checked='<%#Convert.ToBoolean(Eval("....YourColumn...."))%>
<asp:CheckBox ID="CheckBox1" AutoPostBack="true" Checked='<%#Convert.ToBoolean(Eval("....YourColumn...."))%> OnCheckedChanged="myCheckBox_OnCheckedChange" runat="server" Style="text-align: center" />

GridView cannot be delete value asp.net

protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
string strQuery = "select Id, ItemName, FoundAt, TimeIn, ImageName from LostFound order by ID";
SqlCommand cmd = new SqlCommand(strQuery);
SqlConnection con = new SqlConnection(VisitorManagementConnectionString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
ViewState["dt"] = dt;
BindGrid();
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
dt.Dispose();
}
}
protected void BindGrid()
{
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void BtnLose_Click(object sender, EventArgs e)
{
Response.Redirect("SecurityLost.aspx");
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string ID = e.Row.Cells[0].Text;
foreach (Button button in e.Row.Cells[5].Controls.OfType<Button>())
{
if (button.CommandName == "Delete")
{
button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + ID + "?')){ return false; };";
}
}
}
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int ID = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[ID].Delete();
string VisitorManagementConnectionString = ConfigurationManager.ConnectionStrings["VisitorManagementConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(VisitorManagementConnectionString))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM LostFound WHERE ID = #ID"))
{
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
BindGrid();
}
when i press delete button the row can be delete but when i reload the
page the row i deleted still appeal back and my database also never be
deleted.
Can someone guide me where am I going wrong?
<asp:GridView ID="GridView1" runat="server" OnRowDataBound = "OnRowDataBound" AutoGenerateColumns = "false" OnRowDeleting="OnRowDeleting" Font-Names = "Arial" Caption = "Lose & Found" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField = "ID" HeaderText = "ID" />
<asp:BoundField DataField = "ItemName" HeaderText = "Item Name" />
<asp:BoundField DataField = "FoundAt" HeaderText = "Place" />
<asp:BoundField DataField = "TimeIn" HeaderText = "Time Found" />
<asp:ImageField DataImageUrlField = "ID" DataImageUrlFormatString = "Image.aspx?ImageID={0}" ControlStyle-Width = "100" ControlStyle-Height = "100" HeaderText = "Preview Image"/>
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
This my HTML file.
So from the comments we've established that the problem is that your ID is always 0.To make sure the ID comes through correctly you need to make two changes:
1.Change the Page_Load() event like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
//Cut and paste the code to bind to the GridView here
}
}
2.Add this code to the RowDeleting event:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Int32.Parse(GridView1.Rows[e.RowIndex].Cells[0].Text);
}

asp.net c# send ArrayList to gridview not displaying items

I have 3 dropdownlist: select year, select make, select model. Upon select model the results should appear in a gridview. My tables are:
Makes with [(pk)MakeID, MakeName]; Models with [(pk)ModelID, Make_ID, ModelYear, ModelName]; and Wipers with [(pk)WiperID, Model_ID, Description, Emplacement, Price]. When I step through debug, I see 6 counts of records found, but I do not see it in gridview
I've looked at these for help, but no answers
ASP.net DropDownList populates GridView
Binding gridview with arraylist asp.net/c#
My Default.aspx
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="wrapper" align="center">
<asp:DropDownList ID="ddlYear" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="Year_Changed">
</asp:DropDownList>
<asp:DropDownList ID="ddlMake" runat="server"
AutoPostBack="true" OnSelectedIndexChanged="Make_Changed">
</asp:DropDownList>
<asp:DropDownList ID="ddlModel" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="Get_Wipers_By_Model">
</asp:DropDownList>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<asp:GridView ID="grdWiperList" runat="server">
</asp:GridView>
</form>
My Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Year drop down list is populated on page load
string query = "SELECT DISTINCT ModelYear FROM Models";
string connectionString = ConfigurationManager.ConnectionStrings["wiperConnectionString"].ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddlYear.DataSource = cmd.ExecuteReader();
ddlYear.DataValueField = "ModelYear";
ddlYear.DataBind();
conn.Close();
}
}
ddlYear.Items.Insert(0, new ListItem("Select Year", "0"));
ddlMake.Enabled = false;
ddlModel.Enabled = false;
ddlMake.Items.Insert(0, new ListItem("Select Make", "0"));
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
}
}
private void BindDropDownList(DropDownList ddl, string query, string text, string value, string defaultText)
{
string connectionString = ConfigurationManager.ConnectionStrings["wiperConnectionString"].ToString();
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = conn;
conn.Open();
ddl.DataSource = cmd.ExecuteReader();
ddl.DataTextField = text;
ddl.DataValueField = value;
ddl.DataBind();
conn.Close();
}
}
ddl.Items.Insert(0, new ListItem(defaultText, "0"));
}
protected void Year_Changed(object sender, EventArgs e)
{
//the Makes drop down list is populated on OnSelectedIndexChange event of the Year_Changed event
ddlMake.Enabled = false;
ddlModel.Enabled = false;
ddlMake.Items.Clear();
ddlModel.Items.Clear();
ddlMake.Items.Insert(0, new ListItem("Select Make", "0"));
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
int yearId = int.Parse(ddlYear.SelectedItem.Value);
if (yearId > 0)
{
string query = string.Format("SELECT DISTINCT MakeID, MakeName FROM Makes JOIN Models ON Make_ID = MakeID WHERE ModelYear = {0}", yearId);
BindDropDownList(ddlMake, query, "MakeName", "MakeID", "Select Make");
ddlMake.Enabled = true;
}
}
protected void Make_Changed(object sender, EventArgs e)
{
ddlModel.Enabled = false;
ddlModel.Items.Clear();
ddlModel.Items.Insert(0, new ListItem("Select Model", "0"));
int yearID = int.Parse(ddlYear.SelectedItem.Value);
int makeId = int.Parse(ddlMake.SelectedItem.Value);
if (makeId > 0)
{
string query = string.Format("SELECT ModelID, ModelName FROM Models WHERE ModelYear = {0} AND Make_ID = {1}", yearID, makeId);
BindDropDownList(ddlModel, query, "ModelName", "ModelID", "Select Model");
ddlModel.Enabled = true;
}
}
protected void Get_Wipers_By_Model(object sender, EventArgs e)
{
grdWiperList.DataSource = Connection.GetWipersByModel
(!IsPostBack ? "%" : ddlModel.SelectedValue);
grdWiperList.DataBind();
}
}
My Connection.cs
public static ArrayList GetWipersByModel(string modelType)
{
ArrayList listResults = new ArrayList();
string query = string.Format
("SELECT * FROM Wipers WHERE Model_ID LIKE '{0}'", modelType);
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = query;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int wiperID = reader.GetInt32(0);
int model_id = reader.GetInt32(1);
string description = reader.GetString(2);
string itemNo = reader.GetString(3);
string emplacement = reader.GetString(4);
decimal price = reader.GetDecimal(5);
Wipers wipers = new Wipers(wiperID, model_id, description, itemNo, emplacement, price);
listResults.Add(wipers);
}
}
finally
{
conn.Close();
}
return listResults;
}
I think this because the updatePanel control try to add trigger between UpdatePanel control and DropDownList Control

How to hide or make it visible based on the condition given in the TextChanged event of the Textbox?

I am having a textbox on my web form. Within this textbox I am using Jquery Auto Complete. I have taken two labels on my web form and trying to hide this label based on the condition I have given in the TextChanged event of the Textbox. But I am not able display the visible one.
This is my aspx page-
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
var items=[<%=autotag %>];
$("#TextBox1").autocomplete({
source:items
});
});
</script>
<table>
<tr>
<td>Name:</td>
<td>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged1"
AutoPostBack="True"></asp:TextBox></td>
</tr>
<tr><td colspan="2">
<asp:Panel ID="Panel1" runat="server" Visible="False">
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<br />
<asp:Label ID="Label2" runat="server" Text=""></asp:Label></asp:Panel>
</td></tr>
</table>
My cs page-
public string autotag="";
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
bind1();
}
}
//This bind1() is for autocomplete.
public void bind1()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
con.Open();
string query="select name from tbl_data_show";
SqlCommand cmd=new SqlCommand(query,con);
SqlDataReader dr=cmd.ExecuteReader();
dr.Read();
while(dr.Read())
{
if(string.IsNullOrEmpty(autotag))
{
autotag+="\""+dr["name"].ToString()+"\"";
}
else
{
autotag+=", \""+dr["name"].ToString()+"\"";
}
}
}
protected void TextBox1_TextChanged1(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select name from tbl_data_show where name='"+TextBox1.Text+"'", con);
//DataTable dt1 = new DataTable();
//SqlDataAdapter da = new SqlDataAdapter(cmd);
//da.Fill(dt1);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Panel1.Visible = true;
}
}
else
{
Panel1.Visible = false;
}
con.Close();
}
Please guide me where I am doing wrong?
If am not wrong, please try by setting autopostback = true, change your asp tag line like this,
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged1" AutoPostBack="True"></asp:TextBox>
Update
Try your coding in this way,
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
bind1();
//Panel1.Visible = true;
}
}
protected void TextBox1_TextChanged1(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select name from tbl_data_show where name='"+TextBox1.Text+"'", con);
// DataTable dt1 = new DataTable();
// SqlDataAdapter da = new SqlDataAdapter(cmd);
// da.Fill(dt1);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
Panel1.Visible = true;
//if (dt1.Rows.Count > 0)
//{
// if (TextBox1.Text == dr.GetString(0))
// {
// //Label1.Text = "4";
// //Label2.Text = "5";
// Panel1.Visible=true;
// //Label1.Visible = true;
// //Label2.Visible = false;
// }
// else
// {
// //Label2.Text = "5";
// Panel1.Visible = false;
// //Label2.Visible = true;
// //Label1.Visible = false;
// }
//}
}
}
else
{
Panel1.Visible = false;
}
con.Close();
}
Let me know, if you get struggle with this again.
Autocomplete Using Ajax :
Initially download ajaxcontrolkit from this link, and then add into your project using this link and then add this line into your source page (below to <%# page>)
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
aspx :
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged1"
AutoPostBack="True"></asp:TextBox>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:AutoCompleteExtender ServiceMethod="SearchCustomers"
MinimumPrefixLength="1"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
TargetControlID="TextBox1"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false">
Code Behind :
protected void Page_Load(object sender, EventArgs e)
{
//bind1();
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchCustomers(string prefixText, int count)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["conn"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select name from tbl_data_show where " +
"name like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> customers = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(sdr["name"].ToString());
}
}
conn.Close();
return customers;
}
}
}
if you are not setting Lable visibility false anywhere else, try this
protected void TextBox1_TextChanged1(object sender, EventArgs e)
{
dt = g1.return_dt("select name from tbl_data_show");
if (dt.Rows.Count > 0)
{
if (TextBox1.Text == dt.Rows[0]["name"])
{
Label1.Text = "4";
Label1.Visible = true;
}
else if (TextBox1.Text != dt.Rows[0]["name"])
{
Label2.Text = "5";
Label2.Visible = true;
}
else
{
Label1.Visible = false;
Label2.Visible = false;
}
}
}

GridView RowUpdating returns old values after PostBack

I got a problem with my GridView. When I try to edit my GridView, I only get the old values in return.
Here's the RowUpdating event:
protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox nVorname = (TextBox)row.FindControl("newVorname");
TextBox nNachname = (TextBox)row.FindControl("newNachname");
TextBox nTelnr = (TextBox)row.FindControl("newTelnr");
TextBox nEmail = (TextBox)row.FindControl("newEmail");
HiddenField tid = (HiddenField)row.FindControl("id");
grid.EditIndex = -1;
SqlConnection sqlConn = new SqlConnection("server=localhost;Integrated Security=true;database=Telefonbuch;");
sqlConn.Open();
SqlCommand cmd = new SqlCommand("update dasOertliche set vorname= #vorname, nachname=#nachname, telefonnr =#telnr, email =#email where id = #id", sqlConn);
cmd.Parameters.Add("#vorname", SqlDbType.VarChar);
cmd.Parameters["#vorname"].Value = nVorname;
cmd.Parameters.Add("#nachname", SqlDbType.VarChar);
cmd.Parameters["#nachname"].Value = nNachname.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar);
cmd.Parameters["#email"].Value = nEmail.Text;
cmd.Parameters.Add("#telnr", SqlDbType.VarChar);
cmd.Parameters["#telnr"].Value = nTelnr.Text;
cmd.Parameters.Add("#id", SqlDbType.Int);
cmd.Parameters["#id"].Value = tid.Value;
cmd.ExecuteNonQuery();
sqlConn.Close();
bind();
}
The TemplateField from the .aspx:
<Columns>
<asp:TemplateField HeaderText = "Vorname">
<ItemTemplate> <%#Eval ("vorname") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="newVorname" runat="server" Text='<%#Eval ("vorname") %>'>
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</columns>
And my GridView code:
<asp:GridView runat="server" ID="grid" BorderWidth="0px" CellPadding="10"
CellSpacing="10" HorizontalAlign="Center" AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True" onrowcancelingedit="grid_RowCancelingEdit"
onrowediting="grid_RowEditing" onrowupdating="grid_RowUpdating"
AutoGenerateColumns="False">
Like I said, it always returns the old values. Any suggestions?
My Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
bind();
if (!Page.IsPostBack)
{
bind();
}
}
My bind():
public void bind()
{
SqlConnection sqlConn = new SqlConnection("server=localhost;Integrated Security=true;database=Telefonbuch;");
sqlConn.Open();
SqlDataAdapter sqlComm = new SqlDataAdapter("SELECT id, vorname AS 'Vorname', nachname AS 'Nachname', telefonnr, email AS 'E-Mail' FROM dasOertliche ORDER BY nachname ASC", sqlConn);
DataSet ds = new DataSet();
sqlComm.Fill(ds, "dasOertliche");
grid.DataSource = ds.Tables[0];
grid.DataBind();
sqlConn.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
bind();
if (!Page.IsPostBack)
{
bind();
}
}
is wrong.
It should be:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bind();
}
}
On Pageload put your bind grid code in following condition
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bind();
}
}
You need to call GridView1.DataBind() in the end.

Categories

Resources