What I have
I have a gridview bounded to a some Datasource. Inside that i have added another column ("Resources") explicitly bounded to another datasource.
Code.aspx
<asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" runat="server" AutoGenerateColumns="False" DataSourceID="EntityDataSource1">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" SortExpression="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" ReadOnly="True" SortExpression="Description" />
<asp:BoundField DataField="TFSId" HeaderText="TFSId" ReadOnly="True" SortExpression="TFSId" />
<asp:CheckBoxField DataField="IsBillable" HeaderText="IsBillable" ReadOnly="True" SortExpression="IsBillable" />
<asp:BoundField DataField="Estimate" HeaderText="Estimate" ReadOnly="True" SortExpression="Estimate" />
<asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True" SortExpression="Id" />
<asp:TemplateField HeaderText="Resources">
<ItemTemplate >
<asp:UpdatePanel ID="updatepanel1" runat="server" >
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server" Width="100px"></asp:TextBox>
<asp:PopupControlExtender ID="TextBox1_PopupControlExtender" runat="server"
Enabled="True" TargetControlID="TextBox1"
PopupControlID="Panel1" OffsetY="22">
</asp:PopupControlExtender>
<asp:Panel ID="Panel1" runat="server" Height="116px" Width="145px"
BorderStyle="Solid" BorderWidth="2px" Direction="LeftToRight"
ScrollBars="Auto" BackColor="#CCCCCC" Style="display: none">
<asp:CheckBoxList ID="CheckBoxList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="UserId"
DataValueField="UserId" AutoPostBack="True"
OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:42HNetDbConnectionString %>"
SelectCommand="SELECT DISTINCT [UserId] FROM [Resources]">
</asp:SqlDataSource>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
What I want:
I have been able to display all the names of resources as soon as user click the textbox. user can select as many resources as he/she wants. I need to achieve following:
1.I want to show the comma separated names of all the resources as soon as the user clicks on the checkboxlist. For that purpose I have created onselectedindexchanged event.
2.I also want some idea that how to remember what user has selected last time as it is not remembering.
What I tried:
Code Behind
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
/*
string name = "";
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
name += CheckBoxList1.Items[i].Text + ",";
}
}
TextBox1.Text = name;*/
}
The real problem is i'm not able to access CheckBoxList inside onselectedindexchanged event.
How to access textbox, label inside update panel from code behind using asp.net web forms seems to be less helpful.
Any help would be appreciated. Thanks!!!
Finally I got it:
Code Behind
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
for (int j = 0; j < GridView1.Rows.Count; j++)
{
UpdatePanel up1 = GridView1.Rows[j].FindControl("updatepanel1") as UpdatePanel;
TextBox tb1 = up1.FindControl("TextBox1") as TextBox;
CheckBoxList cb1 = up1.FindControl("CheckBoxList1") as CheckBoxList;
string name = "";
for (int i = 0; i < cb1.Items.Count; i++)
{
if (cb1.Items[i].Selected)
{
name += cb1.Items[i].Text + ",";
}
}
tb1.Text = name;
}
}
string strVendorId = string.Empty;
var vender = new StringBuilder();
var vendorcollection = cmbVendorId.CheckedItems;
foreach (var item in vendorcollection)
vender.Append(item.Value + ",");
strVendorId = vender.ToString();
if (strVendorId != "")
{
strVendorId = strVendorId.Remove(strVendorId.Length - 1, 1);
}
U can use this code as a reference code for comma separate
Related
I have a table which contains recipe for each item. Actually I wanted to update my specific column in the table. This table contains Item ID,Stock Code,Stock Name,Stock Group Name,Stock Unit Name,Amount Needed indexes. First of all ı could update and it is working, but when I want to update only my Amount column but when I press edit button, the TextBox opens for each columns. I want only amount row for the TextBox open.
This is the code:
<asp:GridView ID="grdItems" runat="server" DataKeyNames="_IdItemHam" CssClass="table" AutoGenerateColumns="False" ShowHeaderWhenEmpty="False" BorderWidth="0px" GridLines="Horizontal" OnRowDeleting="grdItems_RowDeleting" OnRowEditing="grdItems_RowEdit" meta:resourcekey="GridView5Resource1" >
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="btnSelect" runat="server" CausesValidation="false" CommandName="Delete" Text="Delete" BackColor="DarkRed" style="color: White" />
<%-- <asp:Button ID="btnUpdate" runat="server" CausesValidation="false" CommandName="Update" Text="Update" BackColor="Green" style="color: White" />
--%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Edit" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button Text="Update" runat="server" OnClick="OnUpdate" BackColor="Green" style="color: White" />
<asp:Button Text="Cancel" runat="server" OnClick="OnCancel" BackColor="DarkRed" style="color: White"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="_IdItemHam" HeaderText="Item ID" SortExpression="_IdItemHam" meta:resourcekey="BoundFieldResource9" />
<asp:BoundField DataField="item_code" HeaderText="Item Code" SortExpression="item_code" meta:resourcekey="BoundFieldResource1" />
<asp:BoundField DataField="item_name" HeaderText="Item Name" SortExpression="item_name" meta:resourcekey="BoundFieldResource2" />
<asp:BoundField DataField="item_group_name" HeaderText="Item Group Name" SortExpression="item_group_name" meta:resourcekey="BoundFieldResource3" />
<asp:BoundField DataField="item_unit_name" HeaderText="Item Unit" SortExpression="item_unit_name" meta:resourcekey="BoundFieldResource4" />
<asp:BoundField DataField="_Amount" HeaderText="Amount Needed" SortExpression="_Amount" ReadOnly="false" meta:resourcekey="BoundFieldResource6" />
<%--<asp:BoundField DataField="PROC" HeaderText="PROC" SortExpression="PROC" meta:resourcekey="BoundFieldResource8" />--%>
</Columns>
<SelectedRowStyle BackColor="#CCCCFF" />
</asp:GridView>
And here is my .cs code:
protected void OnUpdate(object sender, EventArgs e)
{
GridViewRow row = (sender as Button).NamingContainer as GridViewRow;
string amount = (row.Cells[6].Controls[0] as TextBox).Text;
//DataTable dt = ViewState["dt"] as DataTable;
//dt.Rows[row.RowIndex]["Amount Needed"] = amount;
//ViewState["dt"] = dt;
((StockRecipe.StockRecipeItemSet)ViewState["StockRecipeItemSet"]).RawMaterials.ElementAt(grdItems.EditIndex)._Amount = Double.Parse(amount);
grdItems.EditIndex = -1;
grdItems.DataSource = ((StockRecipe.StockRecipeItemSet)ViewState["StockRecipeItemSet"]).RawMaterials;
grdItems.DataBind();
CalculateProductCost();
}
Can you please help me about how to make that event. Thanks from now!
I would suggest you use the event OnRowUpdating, implemented in the GridView.
After that you can get the values and keys in the event, do your save statement and bind the grid.
<asp:GridView ID="grdItems" runat="server" DataKeyNames="_IdItemHam" CssClass="table" AutoGenerateColumns="False" ShowHeaderWhenEmpty="False" BorderWidth="0px" GridLines="Horizontal"
OnRowUpdating="grdItems_RowUpdating">
.cs code:
protected void grdItems_RowUpdating(object sender, GridViewUpdateEventArgs e){
object id = e.Keys["_IdItemHam"];
int amount = Convert.ToInt32(e.NewValues["_Amount"]);
//Do your update statment
//After that bind the grid
grdItems.DataBind();
}
use GridView_RowCommand to implement edit action
protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = 0;
GridViewRow row;
GridView grid = sender as GridView;
switch (e.CommandName)
{
case "Edit":
index = Convert.ToInt32(e.CommandArgument);
row = grid.Rows[index];
//use row to find the selected controls you need for edit, update, delete here
break;
}
}
This question already has answers here:
ASP GridView get row values on button click
(2 answers)
Closed 7 years ago.
I have declared a gridview where some fields are bound from database. I have added a item template where I have got a textbox and button. Now when I click the button, I want to catch the values of a column and that textbox of that corresponding row. How can I get it done?
My aspx gridview markup:
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataKeyNames="FOODITEM_ID" DataSourceID="SqlDataSource2" EnableModelValidation="True" OnSelectedIndexChanged="GridView2_SelectedIndexChanged"
OnRowCommand="GridView2_OnRowCommand">
<Columns>
<asp:BoundField DataField="FOOD_ITEM_NAME" HeaderText="FOOD_ITEM_NAME" SortExpression="FOOD_ITEM_NAME" />
<asp:BoundField DataField="FOODITEM_ID" HeaderText="FOODITEM_ID" ReadOnly="True" SortExpression="FOODITEM_ID" />
<asp:BoundField DataField="PRICE" HeaderText="PRICE" SortExpression="PRICE" />
<asp:BoundField DataField="DAY_AVAILABLE" HeaderText="DAY_AVAILABLE" SortExpression="DAY_AVAILABLE" />
<asp:BoundField DataField="TIME_AVAILABLE" HeaderText="TIME_AVAILABLE" SortExpression="TIME_AVAILABLE" />
<asp:BoundField DataField="DISCOUNT_PERCENTAGE" HeaderText="DISCOUNT_PERCENTAGE" SortExpression="DISCOUNT_PERCENTAGE" />
<asp:BoundField DataField="START_DATE" HeaderText="START_DATE" SortExpression="START_DATE" />
<asp:BoundField DataField="DEADLINE" HeaderText="DEADLINE" SortExpression="DEADLINE" />
<asp:BoundField DataField="Rating" HeaderText="Rating" SortExpression="Rating" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="Add"
Text="Add" CommandArgument='<%# ((GridViewRow) Container).RowIndex %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now when I press the the button, how can i get the textbox and other fields' values of that corresponding row.
There are coupe of things you are missing, so I have decided to give you mine complete sample.
First aspx code. Take notice I use CommandNames (Edit, Delete, Cancel, Update) for appropriate command.
Second, I have binded "ItemsGridView_RowUpdating" to catch new values (this is what are you looking for).
<asp:GridView ID="ItemsGridView" runat="server" DataKeyNames="ItemId,FieldName" PageSize="1000"
AutoGenerateColumns="False" AllowPaging="False" AllowSorting="False" SkinID="DefaultGridView"
OnRowEditing="ItemsGridView_RowEditing"
OnRowCancelingEdit="ItemsGridView_RowCancelingEdit"
OnRowDeleting="ItemsGridView_RowDeleting"
OnRowUpdating="ItemsGridView_RowUpdating"
>
<Columns>
<asp:TemplateField ItemStyle-CssClass="TemplateFieldFourColumns">
<ItemTemplate>
<asp:ImageButton ID="ibEdit" runat="server" ToolTip="<% $resources:AppResource,Edit %>" SkinID="EditPage" CommandName="Edit" />
<asp:ImageButton ID="ibDelete" runat="server" ToolTip="<% $resources:AppResource,Delete %>" SkinID="DeletePage" CommandName="Delete" OnClientClick='<%#this.GetDeleteConfirmation() %>' />
<asp:ImageButton ID="ibUp" runat="server" ToolTip="<% $resources:AppResource,Up %>" SkinID="UpPage" OnClick="ibUp_Click" CommandArgument='<%#Eval("ItemId")%>' />
<asp:ImageButton ID="ibDown" runat="server" ToolTip="<% $resources:AppResource,Down %>" SkinID="DownPage" OnClick="ibDown_Click" CommandArgument='<%#Eval("ItemId")%>' />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="ibCancel" runat="server" ToolTip="<% $resources:AppResource,Cancel %>" SkinID="Cancel" CommandName="Cancel" />
<asp:ImageButton ID="ibUpdate" runat="server" ToolTip="<% $resources:AppResource,Save %>" SkinID="Save" CommandName="Update" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="<% $resources:AppResource,Format %>">
<ItemTemplate>
<asp:Label ID="lblFormat" runat="server" Text='<%#Eval("Format")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFormat" runat="server" Text='<%#Bind("Format")%>' Width="50"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Nov code behind:
protected void ItemsGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
ItemsGridView.EditIndex = e.NewEditIndex;
ItemsGridView.DataSource = this.genericForm.FormItems; //TODO: get your data source
ItemsGridView.DataBind();
}
protected void ItemsGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
ItemsGridView.EditIndex = -1;
ItemsGridView.DataSource = this.genericForm.FormItems; //TODO: get your data source
ItemsGridView.DataBind();
}
protected void ItemsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//delete...
try
{
Guid itemId = (Guid)e.Keys[0]; //key
//TODO: delete your item and bind new data
}
catch (Exception ex)
{
this.MessageBoxError(ex);
}
}
protected void ItemsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//update...
try
{
//get your key and read new values for update....
Guid itemId = (Guid)e.Keys[0];
string fieldName = (string)e.Keys[1];
string Format = (string)e.NewValues["Format"];
//TODO: make an update and rebind your data
}
catch (Exception ex)
{
this.MessageBoxError(ex);
}
}
Happy coding!
Flowwing code should work:
void GridView2_OnRowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Add")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = CustomersGridView.Rows[index];
string otherFieldText = row.Cells[0].Text; // put othe fields' index
TextBox txt = (TextBox)row.FindControl("TextBox1"); // Textbox
string txtVal = txt.text; // Textbox value
}
}
I've a Nested grid and check box in parent and child grid. There is a main checkbox at parent grid header to select all data. Then there is another check box against parent row and third check box against every child row.
first two checkboxes and events are working fine.
Issue is with child grid checkbox. when I check the checkbox the event gets fired as expected. But when the checkbox is unchecked the event doesn't get fired. instead it is just posting back.
Code is as below.
<asp:GridView ID="grdmaster" runat="server" SkinID="GridView" AutoGenerateColumns="false" DataKeyNames="ProjectNo" HorizontalAlign="Center" HeaderStyle-Height="35px" OnRowDataBound ="grdmaster_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="View Forging">
<ItemTemplate>
<img alt="" style="cursor: pointer" src="images/plus1.png" />
<asp:Panel ID="pnlforginfo" runat="server" Style="display: none">
<asp:GridView ID ="gvforgmst" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid" ShowHeaderWhenEmpty="true" EmptyDataText="No Data Found" SkinID="GridView">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="ForgingNo" HeaderText="Forging No" />
<asp:BoundField ItemStyle-Width="150px" DataField="ProductType" HeaderText="Product" />
<asp:TemplateField ControlStyle-Height="35px">
<ItemTemplate>
<asp:CheckBox ID="chkviewforg" runat="server" AutoPostBack ="true" OnCheckedChanged="chkviewforg_CheckedChanged" ViewStateMode="Enabled" EnableViewState="True" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="ProjectNo" DataField="ProjectNo" />
<asp:BoundField HeaderText="CustomerName" DataField="CustomerName" />
<asp:BoundField HeaderText="GradCode" DataField="GradCode" />
<asp:TemplateField ControlStyle-Height="35px">
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server"
AutoPostBack="true" OnCheckedChanged="chkAll_CheckedChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server"
AutoPostBack="true" OnCheckedChanged="chk_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void chkviewforg_CheckedChanged(object sender, EventArgs e)
{
int cnt = 0;
CheckBox chkAll = (CheckBox)grdmaster.HeaderRow.Cells[4].FindControl("chkAll");
for (int i = 0; i < grdmaster.Rows.Count; i++)
{
GridView gvforgmst = (GridView)grdmaster.Rows[i].FindControl("gvforgmst");
CheckBox chk = (CheckBox)grdmaster.Rows[i]
.Cells[4].FindControl("chk");
foreach (GridViewRow gr in gvforgmst.Rows)
{
CheckBox chkviewforg = ((CheckBox)gr.FindControl("chkviewforg"));
if (chkviewforg.Checked)
{
cnt++;
}
}
if (gvforgmst.Rows.Count > 0)
{
if (cnt == gvforgmst.Rows.Count)
{
chk.Checked = true;
}
else
{
chk.Checked = false;
chkAll.Checked = false;
}
}
}
}
I have a gridview, which gets info by parametrized sqldatasource. I want to fire up a function by pressing a button, sending one of the fields (id).
But function won't even fire up..
here's my aspx part:
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:igroup20_test2ConnectionString %>"
SelectCommand="select mie.e_num, mie.id, m.f_name, m.l_name from memberInEvent mie, member m where e_num=#num and mie.id=m.id" >
<SelectParameters>
<asp:Parameter DefaultValue="066643776" Name="num" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:PlaceHolder ID="head_line_ph" runat="server"></asp:PlaceHolder>
<br /><br />
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="false" CssClass="tableStatic">
<Columns>
<asp:TemplateField HeaderText="הסר מאירוע">
<ItemTemplate>
<asp:Button ID="delete_mem" CommandArgument='<%# Bind("id") %>' runat="server" Text="הסר מאירוע" OnClick="remove_member" CssClass="btn btn-primary" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ReadOnly="True" HeaderText="ת.ז"
InsertVisible="False" DataField="id"
SortExpression="ת.ז">
</asp:BoundField>
<asp:BoundField ReadOnly="True" HeaderText="שם פרטי"
InsertVisible="False" DataField="f_name"
SortExpression="שם פרטי">
</asp:BoundField>
<asp:BoundField ReadOnly="True" HeaderText="שם משפחה"
InsertVisible="False" DataField="l_name"
SortExpression="שם משפחה">
</asp:BoundField>
</Columns>
</asp:GridView>
here's my code behind:
protected void Page_Load(object sender, EventArgs e)
{
string e_num = Request.QueryString["enum"];
Label headline_lbl = new Label();
headline_lbl.Text = db.return_event_name(e_num);
headline_lbl.CssClass = "head_line";
head_line_ph.Controls.Add(headline_lbl);
SqlDataSource2.SelectParameters["num"].DefaultValue = e_num;
GridView1.DataSourceID = "SqlDataSource2";
GridView1.DataBind();
if (!IsPostBack)
{
List<string[]> ids_list = db.return_ids_for_event(Convert.ToInt32(e_num));
foreach (string[] s in ids_list)
{
DropDownList1.Items.Add(new ListItem(s[0], s[1]));
}
}
}
protected void remove_member(object sender, EventArgs e)
{
string mem_id = ((Button)sender).CommandArgument;
db.remove_member(mem_id, num);
Response.Redirect("memberInevents.aspx?enum=" + num);
}
EDIT:
after reading Suhani Mody's answer I changed it to fire on the gridview's rowcommand like that: (but still doesn't fire up)
<asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="false" CssClass="tableStatic">
<Columns>
<asp:TemplateField HeaderText="הסר מאירוע">
<ItemTemplate>
<asp:Button ID="delete_mem" CommandArgument='<%# Bind("id") %>' CommandName="MyRowButton" runat="server" Text="הסר מאירוע" CssClass="btn btn-primary" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ReadOnly="True" HeaderText="ת.ז"
InsertVisible="False" DataField="id"
SortExpression="ת.ז">
</asp:BoundField>
<asp:BoundField ReadOnly="True" HeaderText="שם פרטי"
InsertVisible="False" DataField="f_name"
SortExpression="שם פרטי">
</asp:BoundField>
<asp:BoundField ReadOnly="True" HeaderText="שם משפחה"
InsertVisible="False" DataField="l_name"
SortExpression="שם משפחה">
</asp:BoundField>
</Columns>
</asp:GridView>
cs:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MyRowButton")
{
string mem_id = e.CommandArgument.ToString();
db.remove_member(mem_id, num);
Response.Redirect("memberInevents.aspx?enum=" + num);
}
}
Put the All code of page load in IsPostBack Block.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string e_num = Request.QueryString["enum"];
Label headline_lbl = new Label();
headline_lbl.Text = db.return_event_name(e_num);
headline_lbl.CssClass = "head_line";
head_line_ph.Controls.Add(headline_lbl);
SqlDataSource2.SelectParameters["num"].DefaultValue = e_num;
GridView1.DataSourceID = "SqlDataSource2";
GridView1.DataBind();
List<string[]> ids_list = db.return_ids_for_event(Convert.ToInt32(e_num));
foreach (string[] s in ids_list)
{
DropDownList1.Items.Add(new ListItem(s[0], s[1]));
}
}
}
If your control (button) is inside a row of a gridview,its event will not fire like how it does for normal buttons. This is called event bubbling. If your controls are inside a container, they become a child of that container.
e.g. in your case, button is a child for gridview and in that case, child cannot fire their events directly. They will send their event to their container/parent i.e. gridview in your case and you need to deal with an event of that parent i.e. gridview.
Try to use OnRowCommand event of your gridview. That should help. You can use "FindControl" method to find your button control on that row.
Hope this helps! Let me know if you need further help.
I think this is your button
<ItemTemplate>
<asp:Button ID="delete_mem" CommandArgument='<%# Bind("id") %>' runat="server" Text="הסר מאירוע" OnClick="remove_member" CssClass="btn btn-primary" />
</ItemTemplate>
Change it to :
<ItemTemplate>
<asp:Button ID="delete_mem" CommandArgument='<%# Eval("id") %>' runat="server" Text="הסר מאירוע" CommandName="remove_member" CssClass="btn btn-primary" />
</ItemTemplate>
Now in gridviews rowcomand event
protectected void Gv_RowCommand(object sender, GridRowCommandEventArgs e)
{
if(e.CommandName.Equals("remove_member"))
{
string mem_id = e.CommandArgument.ToString();
db.remove_member(mem_id, num);
}
System.Thread.Sleep(500); // To hold the current thread for few second to complete the operation and then redirect to your desired page
Response.Redirect("memberInevents.aspx?enum=" + num);
}
See Here
Your old code.
SqlDataSource2.SelectParameters["num"].DefaultValue = e_num;
GridView1.DataSourceID = "SqlDataSource2";
GridView1.DataBind();
if (!IsPostBack)
{
List<string[]> ids_list = db.return_ids_for_event(Convert.ToInt32(e_num));
foreach (string[] s in ids_list)
{
DropDownList1.Items.Add(new ListItem(s[0], s[1]));
}
}
New Code:
SqlDataSource2.SelectParameters["num"].DefaultValue = e_num;
if (!IsPostBack)
{
GridView1.DataSourceID = "SqlDataSource2";
GridView1.DataBind();
List<string[]> ids_list = db.return_ids_for_event(Convert.ToInt32(e_num));
foreach (string[] s in ids_list)
{
DropDownList1.Items.Add(new ListItem(s[0], s[1]));
}
}
Problem:
Binding must be inside !Ispostback
I've been stuck on this for too long, and my Google-Fu is failing me. I'm new to C# and .Net, so I'm getting pretty frustrated here.
Here's what I have so far:
A method called GetData populates a DataSet, then I create a DataTable from that.
I bind the DataTable to the GridView, which is then made sortable. The table and sorting work fine, but I need to have drop down filtering on a few of the columns, but I can't get anything to work.
My ASP:
<asp:GridView id="gvEvaluator" Runat="server" Width="750" tooltip="Evaluator Status" AutoGenerateColumns="False"
EnableViewState="true"
HeaderStyle-ForeColor="#000000"
HeaderStyle-BackColor="#CCCCCC"
FooterStyle-ForeColor="#000000"
FooterStyle-BackColor="#CCCCCC"
Font-Size="8pt"
Font-Names="Verdana"
CellSpacing="0"
CellPadding="3"
ShowFooter="true"
AllowSorting="true"
GridLines="Both"
BorderColor="#ffffff"
BackColor="#ffffff"
ItemStyle-HorizontalAlign="Left"
visible="true"
AllowPaging="false"
AllowCustomPaging="false"
OnSorting="GridView_Sorting">
<Columns>
<asp:TemplateField HeaderText="<strong>Term</strong>"
HeaderStyle-HorizontalAlign="Center" HeaderStyle-VerticalAlign="Bottom"
ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="top" >
<HeaderTemplate>
<asp:DropDownList ID="ddlTerm"
runat="server"
visible="true"
OnSelectedIndexChanged="ddlTermChanged"
AutoPostBack="true"
DataSourceID="gvEvaluator">
</asp:DropDownList>
</HeaderTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Dept" HeaderText="Dept" SortExpression="Dept></asp:BoundField>
<asp:BoundField DataField="Course" HeaderText="Course" SortExpression="Course"></asp:BoundField>
<asp:BoundField DataField="Section" HeaderText="Section"></asp:BoundField>
<asp:BoundField DataField="Evaluator" HeaderText="Evaluator" SortExpression="Evaluator"></asp:BoundField>
<asp:BoundField DataField="Type" HeaderText="Evaluator Type"></asp:BoundField>
<asp:BoundField DataField="Email_Address" Visible="false"></asp:BoundField>
<asp:BoundField DataField="Days_Since_Login" HeaderText="Days Since Login"></asp:BoundField>
<asp:BoundField DataField="Required_Work" HeaderText="Required Work" SortExpression="Required_Work"></asp:BoundField>
<asp:BoundField DataField="Total_Assigned" HeaderText="Total Assigned" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"></asp:BoundField>
<asp:BoundField DataField="Total_Not_Started" HeaderText="Total Not Started" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"></asp:BoundField>
<asp:BoundField DataField="Total_in_Progress" HeaderText="Total in Progress" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"></asp:BoundField>
<asp:BoundField DataField="Total_Complete" HeaderText="Total Complete" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"></asp:BoundField>
<asp:BoundField DataField="eval_id" Visible="false"></asp:BoundField>
<asp:TemplateField HeaderText="<strong>Need Reminder<strong>" ItemStyle-Width="250px">
<ItemTemplate>
<label for="hyplEvaluator" class="hide">Email Evaluator</label>
<asp:HyperLink ID="hyplEvaluator" runat="server" CssClass="BodyLink" Text='<%# DataBinder.Eval(Container, "DataItem.Need_Reminder")%>' NavigateUrl='' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And my C#:
protected void getEvaluatorStatus()
{
try
{
ds = GetData();
DataTable myTable = ds.Tables[0];
if (myTable.Rows.Count != 0)
{
gvEvaluator.DataSource = ds;
gvEvaluator.DataBind();
gvEvaluator.Visible = true;
lblNoAssignment.Visible = false;
}
else
{
lblNoAssignment.Visible = true;
gvEvaluator.Visible = false;
}
//Adds attributes to hyplEmailContact
for (int i = 0; i < gvEvaluator.Rows.Count; i++)
{
string inSenderID = Convert.ToString(meth.decrypt(Session["UserID"].ToString(), Convert.ToString(Session["University"]), Convert.ToString(Session["Department"])));
string inRecptID = Convert.ToString(gvEvaluator.Rows[i].Cells[10].Text);
//custom string of attributes above
string customStr = "inSenderID=" + inSenderID + ",inRecptID=" + inRecptID;
//Adds the NavigateURL for Contact command to pass variables/attributes
HyperLink hyplEmailContact = (HyperLink)gvEvaluator.Rows[i].FindControl("hyplEvaluator");
hyplEmailContact.NavigateUrl = "javascript:openEmailGeneral(" + customStr + ")";
} //End for loop
}
catch (Exception ex)
{
Session["Error_Code"] = ex;
Response.Redirect("../Error.aspx");
}
I'm just a lowly bug squasher, so the only code I personally wrote was creating the GridView (from a DataGrid), the GetData method, making it sortable, and making the data exportable.
Something like this should work:
Handle the ddlTermChanged changed event:
Grab the new selected value in the dropdown list as so
protected void ddlTermChanged(Object sender, EventArgs e) {
var newValue = ddlTerm.SelectedValue;
//see step 3 below
}
Now filter the data and rebind it to the Gridview; something like:
protected void ddlTermChanged(Object sender, EventArgs e) {
var newValue = ddlTerm.SelectedValue;
DataTable t= GetDataByID(newValue);
gvEvaluator.DataSource=t;
gvEvaluator.DataBind();
}
On a separate note, all the transformations you are doing on the Gridview inside the getEvaluatorStatus method should have been handled in the OnRowDataBound event. By doing it the way you did it, every time you rebind the data (as in the case of filtering) you'll have to repeat the code inside the getEvaluatorStatus to do the transformations again. If you do it OnRowDataBound you won't have to repeat code as the event is raised for every row as it is being bound.