Combobox Databind() check - c#

I have a combobox and a list of values in it.
If I add a value and save it, it should appear in the combobox. But it only appears after I refresh the page. It does not bind the data properly.
I have put DataBind() in
if (!Page.IsPostBack)
{
DataBind() ;
}
But the above does not help.
How do I check if everything is binding correctly or not.
Please help.
Thank you
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
if (!Page.IsPostBack)
{
}
}
protected void btn_save_click(object sender, EventArgs e)
{
SqlCommand command_update = new SqlCommand("Update", connection_save1);
command_update.CommandType = System.Data.CommandType.StoredProcedure;
command_update.Parameters.Add(new SqlParameter("#ViewId", Int32.Parse(Id.Value)));
SqlParameter Returns = new SqlParameter("#ReturnCode", SqlDbType.Char);
Returns.Size = 1;
Returns.Direction = ParameterDirection.Output;
command_insert.Parameters.Add(Returns);
bSuccess = command_insert.Parameters["#ReturnCode"].Value.ToString();
if (bSuccess == "1")
{
//Response.Write("Insert successful");
dd_group.DataBind();
dd_group.SelectedValue = command_insert.Parameters["#ReturnCode"].Value.ToString().Trim();
}
}
here is the html
<asp:DropDownList ID="dd_group" DataSourceID="sp" DataTextField="maintitle"
DataValueField="Id" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="group_SelectedIndexChanged1" Height="24px"
Width="50%">
</asp:DropDownList>
<asp:SqlDataSource ID="sp" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="GetIds" runat="server" SelectCommandType="StoredProcedure">

protected void Pre_Render(object sender, EventArgs e)
{
DataBind();
}
protected void btn_save_click(object sender, EventArgs e)
{
SqlCommand command_update = new SqlCommand("Update", connection_save1);
command_update.CommandType = System.Data.CommandType.StoredProcedure;
command_update.Parameters.Add(new SqlParameter("#ViewId", Int32.Parse(Id.Value)));
SqlParameter Returns = new SqlParameter("#ReturnCode", SqlDbType.Char);
Returns.Size = 1;
Returns.Direction = ParameterDirection.Output;
command_insert.Parameters.Add(Returns);
bSuccess = command_insert.Parameters["#ReturnCode"].Value.ToString();
if (bSuccess == "1")
{
//Response.Write("Insert successful");
dd_group.DataBind();
dd_group.SelectedValue = command_insert.Parameters["#ReturnCode"].Value.ToString().Trim();
}
}

you can use a webmethod to add elements to the combobox and when you add any item use jquery or even javascript and call this webmthod where u rebind the data

You have to call DataBind() after you update your data source: this is normally done in some control event handler which is called after Page_Load() event and therefore this invocation is only visible after your refresh (then it is called for the second time, the first time after your update).
So, just add DataBind() to your method where you perform the update, something like:
mycontrol.DataSource = newvariable;
mycontrol.DataBind();

Related

Header DDL in Gridview on ispostback

I have a header DDL in my gridview that for some reason does not keep my selected value but rather binds the gridview and the header back to "starting position"
In my DDL header for Priority i have selected value '99' but after that my header gets back to starting position of my ListItem (that is Priority)
<HeaderTemplate>
<asp:DropDownList ID="ddlPriorityHeader" AutoPostBack="True" AppendDataBoundItems="True" OnSelectedIndexChanged="ddlHeader_SelectedIndexChanged" runat="server">
<asp:ListItem>Priority</asp:ListItem>
</asp:DropDownList>
</HeaderTemplate>
I have a RowDatabound for the gridview but there i do nothing more then find the DDL for the header and then bound the DDL.
protected void gwActivity_RowDataBound(object sender, GridViewRowEventArgs e)
{
//.............. some code.....//
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT DISTINCT [Priority] FROM [BI_Planning].[dbo].[tblPriority]", con);
con.Open();
ddlPriority.DataSource = cmd.ExecuteReader();
ddlPriority.DataTextField = "Priority";
ddlPriority.DataBind();
}
}
I have put my gridview in a method:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewActivity();
}
}
Can it be that im bounding my DDL everytime for my gridview? im stuck here....
You need to store ddlPriority selected text in temp place like ViewState that will keep value between postbacks.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["PriorityText"] = "Priority";
BindGridviewActivity();
}
}
And aftrt ddlPriority.DataBind(); set selectd text to ViewState value
ddlPriority.Items.FindByText(ViewState["PriorityText"].ToString()).Selected = true;
And in your ddlHeader_SelectedIndexChanged set ViewState to selected text
protected void ddlHeader_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlHeader = (DropDownList)sender;
ViewState["PriorityText"] = ddlHeader.SelectedItem.Text;
}
Check this complete example for more details

How to disable a link button in gridview when clicked

I have two LinkButton's called Approve and Reject in my GridView and I want my Approve LinkButton to be Disabled when click on it. I tried the following code but it's not working.
protected void gvManagerTimeSheet_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ApproveRow")
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
LinkButton lnkbtn = (LinkButton)row.FindControl("lbApprove");
lnkbtn.Enabled = false;
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
int TimeSheetId = Convert.ToInt32(e.CommandArgument);
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spApproveTimeSheet ", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#TimeSheetId", TimeSheetId);
con.Open();
cmd.ExecuteNonQuery();
GetManagerTimeSheets();
}
}
}
Well you haven't shown your aspx link button so i assuming that your link button is this
<asp:LinkButton id="linkBtn" runat="server" text="Approve" OnClientClick="Disable(this);"/>
Now you should add a javascript function like this on the page::
<script>
function Disable(link)
{
link.disabled = result;
}
</script>
Now when you click on the page your button will get disabled.
try this
LinkButton lbApprove = (LinkButton)e.Row.Cells[0].Controls[0];
You need to Rebind the grid with disabled control, but also you need to check the status in itembound event and disable. For that you can use session or hidden field.
protected void rg_OnItemCommand(object source, GridCommandEventArgs e)
{
// your logic
hdFlag.value = "val" // id of the data item to hide if more than one use array
// rebind logic for gird
}
protected void rg_ItemDataBound(object sender, GridItemEventArgs e)
{
if(hdFlag.value == "id")
{
// Find the control and hide
}
}

Annoying postback and paging issue

I asked a similar question to this but the circumstances have changed.
I bind my gridview through code rather than on the source.
The pagination works fine, but if I click a button on second page of the gridview (after pagination), the postback is causing the pagination to reset to page 1. Can anyone tell me what I'm doing wrong?
Within my pageload i have set the !POSTBACK method as shown i.e if there is postback event, then it shouldn't reset the grid but it does!
Heres the onload:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["usersName"] != null)
{
object a = Session["_id"];
IDMaster = Convert.ToInt32(a);
GridView1.Columns[10].Visible = true;
GridView1.Columns[11].Visible = true;
}
else
{
GridView1.Columns[10].Visible = false;
GridView1.Columns[11].Visible = false;
}
if (!IsPostBack)
{
BindGrid();
}
The BindGrid();
SqlConnection sqlcon = new SqlConnection(connstring);
SqlCommand sqlcmd = new SqlCommand("select * from Coffees ORDER BY coffeeName ASC", sqlcon);
SqlDataAdapter adp = new SqlDataAdapter(sqlcmd);
DataSet ds = new DataSet();
adp.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
Page index method:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
if(ViewState["searchTerm"] != null)
{
object a = ViewState["searchTerm"];
string reloadTerm = a.ToString();
setGrid(reloadTerm);
}
You need to bind your gridview in GridView1_PageIndexChanging event
GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
if(ViewState["searchTerm"] != null)
{
object a = ViewState["searchTerm"];
string reloadTerm = a.ToString();
setGrid(reloadTerm);
}
BindGrid();
}
hopefully it works for you.
Since you are binding grid view dynamically, Please remove
if (!IsPostBack)
condition from page load. Grid view needs binding every time.
I found this issue. I forgot that after I add an item to my cart i was calling response.redirect to refresh the page....obviously this meant the page was recalled refreshing the page so the grid was always going to reset. Thanks again.

Filtering results in ASP.NET Web Forms

I'm trying to walk through a tutorial on web forms, and my attempts to filter search results isn't working quite right:
The contents of the asp page look like this:
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="button1" runat="server" onclick="button1_Click" Text="Submit" />
<asp:GridView ID="GridView1" AllowPaging="true" PageSize="8" AutoGenerateColumns="false" runat="server"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField HeaderText="Qual ID" DataField="ID" />
<asp:BoundField HeaderText="Client Name" DataField="Client_Name" />
<asp:BoundField HeaderText="Project" DataField="Project_Name" />
<asp:BoundField HeaderText="Uploaded By" DataField="Uploaded_By" />
</Columns>
</asp:GridView>
</form>
And the code behind file:
public partial class Sample1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SourceDataContext db = new SourceDataContext();
GridView1.DataSource = from q in db.Cust
orderby q.ID
select q;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
protected void button1_Click(object sender, EventArgs e)
{
string client = TextBox1.Text;
SourceDataContext db = new SourceDataContext();
GridView1.DataSource = from q in db.Cust
where q.Client_Name == client
orderby q.ID
select q;
GridView1.DataBind();
}
}
The filtering works, although it the paging stops working. Any suggestions appreciated.
Thanks.
it seems to me that there are two problems
on Page_Load enclose binding in !IsPostBack
GridView1_PageIndexChanging do not bind again
see the catch by Chris Gessler
Code
public partial class Sample1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
SourceDataContext db = new SourceDataContext();
GridView1.DataSource = from q in db.Cust
orderby q.ID
select q;
GridView1.DataBind();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
}
protected void button1_Click(object sender, EventArgs e)
{
string client = TextBox1.Text;
SourceDataContext db = new SourceDataContext();
GridView1.DataSource = from q in db.Cust
where q.Client_Name == client
orderby q.ID
select q;
GridView1.DataBind();
GridView1.PageIndex = 0;
}
}
Issue 1: This should only run on GET requests. ViewState will take over on PostBacks and populate the grid.
protected void Page_Load(object sender, EventArgs e)
{
if(!this.Page.IsPostback)
{
SourceDataContext db = new SourceDataContext();
GridView1.DataSource = from q in db.Cust
orderby q.ID
select q;
GridView1.DataBind();
}
}
Issue 2: You need to reset the page index because the recordset changed. The current page may not exist.
protected void button1_Click(object sender, EventArgs e)
{
string client = TextBox1.Text;
SourceDataContext db = new SourceDataContext();
GridView1.DataSource = from q in db.Cust
where q.Client_Name == client
orderby q.ID
select q;
GridView1.DataBind();
GridView1.PageIndex = 0;
}
Issue 3: You're calling DataBind(), but not setting a new datasource.
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
}
Also,
consider caching the recordset and filtering that instead of making a call to the server for a new recordset, however, this depends on "need". Caching a recordset will not find any new records obviously, which may not fit your business need.
consider setting your events in Code Behind in the OnInit method:
protected void Page_Init(object sender, EventArgs e)
{
this.GridView1.PageIndexChanging += GridView1_PageIndexChanging;
}

asp.net gridview dynamically binding

i have a GridView,
<asp:GridView ID="managerList" runat="server" DataSourceID="SqlDataSource2">
in the code behind,
protected void Page_Load(object sender, EventArgs e)
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
when i load the page, it works fine, the paging works fine, too.
Then i want to get the subset of the list by click on a search button:
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlDataSource2.SelectCommand = "select * from manager where age > 30";
managerList.DataBind();
}
it works fine, give me the subset of the list.
However, when i click on "next page", it gives me the whole list, page #2. I know it's because it sends a postback, and it bind the original select command. But how can i do to give me the subset of the list when i click on "next page"?
Thank you!
UPDATES:
if i change the code into this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
}
it gives me an empty list when i click on "next page".
it might be tempted to add IsPostBack, but this not work.
Add the NewPageIndex code in the PageIndexChanging event:
managerList.PageIndex = e.NewPageIndex;
bindgrid();
Below might help you
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
}
You need to put your code under !IsPostBack() in the page_load event. like...
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
}
Reason: Whenever you hit the Next button, your page load event is called before the PageIndexChanging Event handler of Gridview.
Page_Load fires every time the page is loaded, including postbacks, so your select statement is getting reset. Try setting a viewstate value to keep your select statement.
Store the most recent SQL Query in a global static string and then use the following code.
static String previousSQL_Query;
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
SqlDataSource2.SelectCommand = previousSQL_Query;
}
else
{
SqlDataSource2.SelectCommand = "select * from manager";
managerList.AllowPaging = true;
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlDataSource2.SelectCommand = "select * from manager where age > 30";
previousSQL_Query = SqlDataSource2.SelectCommand;
managerList.DataBind();
}

Categories

Resources