ASP.NET Bulk Edit GridView Save button - c#

I use this Bulk Edit GridView Control http://aspnetrealworldcontr.codeplex.com/
I use Linq and have a Stored Procedure to update the database.
I don't Understand how to use the Save Button to update the database.
You are suppose to update all the rows with one button.
In the example they use SqlDataSource
example
<div>
<asp:Button runat="server" ID="SaveButton" Text="Save Data" />
<rwg:BulkEditGridView ID="EditableGrid" DataSourceID="PubsDataSource" AutoGenerateColumns="False"
DataKeyNames="au_id" SaveButtonID="SaveButton" runat="server">
<Columns>
<asp:BoundField HeaderText="Last Name" DataField="au_lname" />
<asp:BoundField HeaderText="First Name" DataField="au_fname" />
<asp:BoundField HeaderText="Phone" DataField="phone" />
<asp:BoundField HeaderText="Address" DataField="address" />
<asp:BoundField HeaderText="City" DataField="city" />
<asp:BoundField HeaderText="State" DataField="state" />
<asp:BoundField HeaderText="Zip Code" DataField="zip" />
<asp:CheckBoxField HeaderText="Contract" DataField="contract" />
</Columns>
</rwg:BulkEditGridView>
<asp:SqlDataSource ID="PubsDataSource" runat="server"
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors]"
UpdateCommand="UPDATE [authors] SET [au_lname] = #au_lname, [au_fname] = #au_fname, [phone] = #phone, [address] = #address, [city] = #city, [state] = #state, [zip] = #zip, [contract]=#contract WHERE [au_id] = #au_id"
ConnectionString="<%$ ConnectionStrings:Pubs %>" />
</div>
My Code - Only the Quantity can be updated.
<cc1:BulkEditGridView ID="CartGrid" runat="server" CssClass="table table-condensed" AutoGenerateColumns="False" GridLines="None" SaveButtonID="UpdateShoppingCart" EnableInsert="False" InsertRowCount="1">
<Columns>
<asp:BoundField DataField="ArtnrFull" HeaderText="Artnr" ReadOnly="True" ItemStyle-Width="10%">
<ItemStyle Width="10%"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="ProductName" HeaderText="Namn" ReadOnly="True" />
<asp:BoundField DataField="Quantity" HeaderText="Antal" ItemStyle-Width="10%">
<ItemStyle Width="10%"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Pris" DataFormatString="{0:c}" HeaderText="Pris" ReadOnly="True" ItemStyle-Width="20%">
<ItemStyle Width="20%"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Subtotal" DataFormatString="{0:c}" HeaderText="Subtotal" ReadOnly="True" ItemStyle-Width="20%">
<ItemStyle Width="20%"></ItemStyle>
</asp:BoundField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" Text="">
<asp:Image ID="Image1" runat="server" ImageUrl="/img/delete.png" Width="20" />
</asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="5%" />
</asp:TemplateField>
<asp:TemplateField Visible="False">
<ItemTemplate>
<asp:Label ID="LblShoppingCartId" runat="server" Text='<%# Bind("ShoppingCartId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</cc1:BulkEditGridView>
<asp:Button ID="UpdateShoppingCart" runat="server" Text="Spara" CssClass="btn btn-success pull-right" />
Stored procedure
CREATE PROCEDURE ShoppingCartUpdateQuantity
#ShoppingCartId int,
#Quantity int,
#ArtnrFull varchar(20)
AS
UPDATE ShoppingCartItems
SET Quantity = #Quantity
WHERE ArtnrFull = #ArtnrFull AND ShoppingCartItems.ShoppingCartId = #ShoppingCartId
Guessing, but this don't runs when i click the button, the grid just disappear.
protected void grdContact_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtQuantity = (TextBox)CartGrid.Rows[e.RowIndex].FindControl("txtQuantity");
Label lblArtnr = (Label)CartGrid.Rows[e.RowIndex].FindControl("lblArtnr");
Label lblShoppingCartId = (Label)CartGrid.Rows[e.RowIndex].FindControl("lblShoppingCartId");
LinqtoDBDataContext db = new LinqtoDBDataContext();
db.ShoppingCartUpdateQuantity(Convert.ToInt32(lblShoppingCartId.Text),Convert.ToInt32(txtQuantity.Text), lblArtnr.Text);
CartGrid.EditIndex = -1;
FillGrid(Convert.ToInt32(lblShoppingCartId.Text));
}

protected void CartGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
if (CartGrid.DirtyRows.Count > 0)
{
Label lblShoppingCartId = (Label)CartGrid.Rows[e.RowIndex].FindControl("lblShoppingCartId");
var cartid = lblShoppingCartId.Text;
//find out which rows were updated
foreach (GridViewRow row in CartGrid.DirtyRows)
{
string lblArtnr = row.Cells[0].Text;
TextBox txtQuantity = row.Cells[2].Controls[0] as TextBox;
LinqtoDBDataContext db = new LinqtoDBDataContext();
db.ShoppingCartUpdateQuantity(Convert.ToInt32(lblShoppingCartId.Text), Convert.ToInt32(txtQuantity.Text), lblArtnr);
}
FillGrid(Convert.ToInt32(cartid));
alertdiv.Attributes.Add("class", "alert alert-success");
alertdiv.Controls.Add(new LiteralControl("Kundvagnen updaterad"));
alertdiv.Visible = true;
}
else
{
alertdiv.Attributes.Add("class", "alert alert-danger");
alertdiv.Controls.Add(new LiteralControl("FEL! Kundvagnen ej updaterad"));
alertdiv.Visible = true;
}
}
catch (Exception)
{
alertdiv.Attributes.Add("class", "alert alert-danger");
alertdiv.Controls.Add(new LiteralControl("FEL! Kundvagnen ej updaterad"));
alertdiv.Visible = true;
}
}

Related

Edit gridview row asp.net without using commandfield

I would like to make a column editable in a gridview but without the edit column (the one with the keys update, cancel ...) due to space problems. I tried to recall the javascript functions related to those buttons in the onRowDataBound but onclick event is not taken. Here my code. Can anyone help me please?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowIndex == GridView1.EditIndex) //GridView is in edit mode
{
//update or cancel buttons
LinkButton updateBtn = (LinkButton)e.Row.Cells[0].Controls[0];
string updateScript = ClientScript.GetPostBackClientHyperlink(updateBtn, "");
Button1.Attributes["onclick"] = updateScript;
string cancelScript = string.Format("javascript:__doPostBack('{0}','Cancel${1}')", GridView1.ID, e.Row.RowIndex);
Button2.Attributes["onclick"] = cancelScript;
}
else //GridView is in read mode
{
//edit button
string editScript = string.Format("javascript:__doPostBack('{0}','Edit${1}')", GridView1.ID, e.Row.RowIndex);
e.Row.Attributes["onclick"] = editScript;
}
}
if (GridView1.EditIndex >= 0)
{
Button1.Enabled = true;
Button2.Enabled = true;
}
else
{
Button1.Enabled = false;
Button2.Enabled = false;
}
}
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="false" DataKeyNames="PKCOD" AllowPaging="True" PageSize="10"
CssClass="auto-style1" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<%--
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="QUANTITA" SortExpression="QUANTITA">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("QUANTITA") %>'></asp:TextBox>
<br />
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox1" EnableClientScript="False" ErrorMessage="ErrorMessage" MaximumValue="999" MinimumValue="0" Type="Integer">Valori tra 0 e 999</asp:RangeValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("QUANTITA") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
--%>
<asp:CommandField ShowEditButton="True" />
<asp:TemplateField HeaderText="QUANTITA" SortExpression="QUANTITA">
<ItemTemplate>
<asp:TextBox ID="textBoxQuantita" runat="server" Text='<%# Bind("QUANTITA") %>'></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" Type="Double" MinimumValue="0" MaximumValue="999" ControlToValidate="textBoxQuantita" runat="server"
ErrorMessage="Inserisci solo numeri compresi tra 0 e 999"></asp:RangeValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CODICE" HeaderText="CODICE" ReadOnly="True" SortExpression="CODICE" />
<asp:BoundField DataField="DESCRIZIONE" HeaderText="DESCRIZIONE" ReadOnly="True" SortExpression="DESCRIZIONE" />
<asp:BoundField DataField="CATEGORIA" HeaderText="CATEGORIA" ReadOnly="True" SortExpression="CATEGORIA" Visible="False" />
<asp:BoundField DataField="PKCOD" HeaderText="PKCOD" ReadOnly="True" SortExpression="PKCOD" InsertVisible="False" Visible="False" />
<asp:BoundField DataField="USERNAME" HeaderText="USERNAME" ReadOnly="True" SortExpression="USERNAME" Visible="False" />
<asp:BoundField DataField="USERID" HeaderText="USERID" ReadOnly="True" SortExpression="USERID" Visible="False" />
<asp:BoundField DataField="USERDT" HeaderText="USERDT" ReadOnly="True" SortExpression="USERDT" Visible="False" />
<asp:BoundField DataField="STATO" HeaderText="STATO" ReadOnly="True" SortExpression="STATO" Visible="False" />
</Columns>
</asp:GridView>

selectedrow on hidden boundfield

I've done my research here and I can now succesfully get a value of a hidden boundfield column in my gridview. The problem is I can't target the a hidden column of the row that I selected.
can I use GridView1.SelectedRow.Cells[7].Text; something like that on a hidden column.Is it possible?
here is my code:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
//GridView1.Columns[7].Visible = true;
//stock_id_gridview_1();
foreach (GridViewRow row in GridView1.Rows)
{
string id = GridView1.DataKeys[row.RowIndex]["id"].ToString();
con.Open();
cmd = new SqlCommand(#"SELECT transaction_id,transaction_number
FROM stocks_history
WHERE id = #id", con);
cmd.Parameters.AddWithValue("#id", id);
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
transaction_id = rdr["transaction_id"].ToString();
//lbl_test_id.Text = rdr["transaction_id"].ToString();
transaction_number = rdr["transaction_number"].ToString();
lbl_test_id.Text = transaction_id + " " + transaction_number;
}
}
con.Close();
}
here is my gridview:
<asp:GridView ID="GridView1"
CssClass="table table-hover table-striped"
runat="server"
AutoGenerateColumns="False" DataKeyNames="id" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="productName" HeaderText="Product Name"
SortExpression="DateField" />
<asp:BoundField DataField="stock_name" HeaderText="Stock Name"
SortExpression="DateField" />
<asp:BoundField DataField="stock_id" HeaderText="Stock I.D."
SortExpression="DateField" />
<asp:BoundField DataField="stock_in" HeaderText="Stock In"
SortExpression="DateField" />
<asp:BoundField DataField="stock_out" HeaderText="Stock Out"
SortExpression="DateField" />
<asp:BoundField DataField="stock_on_hand" HeaderText="On hand"
SortExpression="DateField" />
<asp:BoundField DataField="max_date" HeaderText="Date & Time"
DataFormatString="{0:MM-dd-yyyy hh:mm tt}"
SortExpression="DateField" />
<asp:BoundField DataField="id" Visible="false" HeaderText="id"
SortExpression="DateField" />
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="HiddenField1" runat="server"
Value='<%# Eval("id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField Text="Select" ControlStyle-CssClass="btn btn-info btn-sm" CommandName="Select" ItemStyle-Width="150" HeaderText="Review">
<ControlStyle CssClass="btn btn-info btn-sm"></ControlStyle>
<ItemStyle Width="150px"></ItemStyle>
</asp:ButtonField>
</Columns>
</asp:GridView>
I wanted to target this bound field:
<asp:BoundField DataField="id" Visible="false" HeaderText="id"
SortExpression="DateField" />
If You use attribute DataKeyNames, you can take value from invisible column like
Use Attribute
<asp:GridView runat="server" ID="GridView" DataKeyNames="id">
</asp:GridView>
And you can access the data
var id = GridView.DataKeys[RowIndex].Values[KeyIndex]
To get selected row hidden column value
var id = GridView.DataKeys[GridView.SelectedRow.RowIndex].Values[0];

How to get a refreshed table without refreshing the whole page?

I am developing an ASP.NET intranet web application which is a Quiz Engine. Since I am a new ASP.NET developer, I have a table that shows some feedback received from the users and the admin has the ability to accept or reject these feedback using the DropDownList.
Under this table, there is a JQuery Accordion that when the Admin clicks on it, he will see a table with the received feedback for the last three months. But when the admin accepts or rejects one of the feedback and then clicks on the Accordion, he will see the that table but without that feedback even if the feedback is one of the feedbacks submitted last month. However, when you refresh the page and then clicks on the Accordion, he will see it.
So is there any functionality that will help me to get an auto-refresh table with refreshing the whole page?
Any help please?
ASP.NET Code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID"
width="950px" CssClass="mGrid"
AlternatingRowStyle-CssClass="alt"
RowStyle-HorizontalAlign="Center"
DataSourceID="SqlDataSource1"
OnRowDataBound="GridView1_RowDataBound" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<HeaderStyle Font-Bold = "true" ForeColor="Black" Height="20px"/>
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" />
<asp:BoundField DataField="DivisionShortcut" HeaderText="Division"
SortExpression="DivisionShortcut" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="DropDownList" runat="server" DataSourceID="SqlDataSource2"
Font-Bold="True" ForeColor="#006666" AppendDataBoundItems="false"
DataTextField="Status" DataValueField="ID" AutoPostBack="true"
OnDataBound="DropDownList_DataBound" OnSelectedIndexChanged ="DropDownList_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT dbo.SafetySuggestionsLog.ID, dbo.SafetySuggestionsLog.Title, dbo.SafetySuggestionsLog.Description, dbo.employee.Name, dbo.SafetySuggestionsLog.Username,
dbo.Divisions.DivisionShortcut
FROM dbo.employee INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username INNER JOIN
dbo.Divisions ON dbo.employee.DivisionCode = dbo.Divisions.SapCode"
FilterExpression="[DivisionShortcut] like '{0}%'">
<FilterParameters>
<asp:ControlParameter ControlID="ddlDivision" Name="DivisionShortcut"
PropertyName="SelectedValue" Type="String" />
</FilterParameters>
</asp:SqlDataSource>
<%--For the DropDownList--%>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT * FROM [SafetySuggestionsStatus]">
</asp:SqlDataSource>
<%--Filtering by Division--%>
<asp:SqlDataSource ID="sqlDataSourceDivision" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT [DivisionShortcut] FROM [Divisions]"></asp:SqlDataSource>
<dl id="jfaq">
<br />
<dt>Safety Suggestions List (for the last three months)</dt>
<dd>
<br />
<asp:Panel ID="Panel1" runat="server">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
AllowSorting="True" CssClass="mGrid"
AlternatingRowStyle-CssClass="alt"
RowStyle-HorizontalAlign="Center"
DataSourceID="SqlDataSource4">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<HeaderStyle Font-Bold = "true" ForeColor="Black" Height="20px"/>
<Columns>
<asp:BoundField DataField="SubmittedMonth" HeaderText="Submitted Month"
SortExpression="SubmittedMonth" ReadOnly="True" />
<asp:BoundField DataField="DivisionShortcut" HeaderText="Division"
SortExpression="DivisionShortcut" />
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" />
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
</Columns>
<RowStyle HorizontalAlign="Center"></RowStyle>
</asp:GridView>
</asp:Panel>
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>" SelectCommand="SELECT TOP (100) PERCENT LEFT(DATENAME(month, dbo.SafetySuggestionsLog.DateSubmitted), 3) + '-' + DATENAME(year, dbo.SafetySuggestionsLog.DateSubmitted)
AS SubmittedMonth, dbo.Divisions.DivisionShortcut, dbo.SafetySuggestionsLog.Username, dbo.employee.Name, dbo.SafetySuggestionsLog.Title,
dbo.SafetySuggestionsLog.Description, dbo.SafetySuggestionsType.Type, dbo.SafetySuggestionsStatus.Status
FROM dbo.Divisions INNER JOIN
dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username INNER JOIN
dbo.SafetySuggestionsType ON dbo.SafetySuggestionsLog.TypeID = dbo.SafetySuggestionsType.ID INNER JOIN
dbo.SafetySuggestionsStatus ON dbo.SafetySuggestionsLog.StatusID = dbo.SafetySuggestionsStatus.ID
WHERE (DATEDIFF(month, dbo.SafetySuggestionsLog.DateSubmitted, GETDATE()) < 3)
ORDER BY dbo.SafetySuggestionsLog.DateSubmitted DESC">
</asp:SqlDataSource>
<asp:Button ID="btnPrint" runat="server" Text="Print" OnClick="btnPrint_Click" />
</dd>
</dl>
Code-Behind:
protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
int suggestionStatus = int.Parse(ddl.SelectedValue);
GridViewRow row = (GridViewRow)ddl.NamingContainer;
string strID = GridView1.DataKeys[row.RowIndex]["ID"].ToString();
int ID = Int32.Parse(strID);
//For inserting the status in the database
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdbTest;Integrated Security=True";
string updateCommand = "UPDATE SafetySuggestionsLog SET [StatusID] = #StatusID WHERE [ID] = #ID";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(updateCommand, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#StatusID", suggestionStatus);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
UPDATE:
I used the UpdatePanel control to get a partial update, and I used <triggers>, but I got the following error and I don't know why:
Could not find an event named 'Click' on associated control
'GridView2' for the trigger in UpdatePanel 'UpdatePanel1'.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView2" EventName="Click" />
</Triggers>
<ContentTemplate>
<dl id="jfaq">
<br />
<dt>Safety Suggestions List (for the last three months)</dt>
<dd>
<br />
<asp:Panel ID="Panel1" runat="server">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
AllowSorting="True" CssClass="mGrid"
AlternatingRowStyle-CssClass="alt"
RowStyle-HorizontalAlign="Center"
DataSourceID="SqlDataSource4">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<HeaderStyle Font-Bold = "true" ForeColor="Black" Height="20px"/>
<Columns>
<asp:BoundField DataField="SubmittedMonth" HeaderText="Submitted Month"
SortExpression="SubmittedMonth" ReadOnly="True" />
<asp:BoundField DataField="DivisionShortcut" HeaderText="Division"
SortExpression="DivisionShortcut" />
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" />
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
</Columns>
<RowStyle HorizontalAlign="Center"></RowStyle>
</asp:GridView>
</asp:Panel>
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>" SelectCommand="SELECT TOP (100) PERCENT LEFT(DATENAME(month, dbo.SafetySuggestionsLog.DateSubmitted), 3) + '-' + DATENAME(year, dbo.SafetySuggestionsLog.DateSubmitted)
AS SubmittedMonth, dbo.Divisions.DivisionShortcut, dbo.SafetySuggestionsLog.Username, dbo.employee.Name, dbo.SafetySuggestionsLog.Title,
dbo.SafetySuggestionsLog.Description, dbo.SafetySuggestionsType.Type, dbo.SafetySuggestionsStatus.Status
FROM dbo.Divisions INNER JOIN
dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username INNER JOIN
dbo.SafetySuggestionsType ON dbo.SafetySuggestionsLog.TypeID = dbo.SafetySuggestionsType.ID INNER JOIN
dbo.SafetySuggestionsStatus ON dbo.SafetySuggestionsLog.StatusID = dbo.SafetySuggestionsStatus.ID
WHERE (DATEDIFF(month, dbo.SafetySuggestionsLog.DateSubmitted, GETDATE()) < 3)
ORDER BY dbo.SafetySuggestionsLog.DateSubmitted DESC">
</asp:SqlDataSource>
<asp:Button ID="btnPrint" runat="server" Text="Print" OnClick="btnPrint_Click" />
</dd>
</dl>
</ContentTemplate>
</asp:UpdatePanel>
In the trigger you mentioned Click event, but in the code behind you have only DropDownList_SelectedIndexChanged event.
Instead you can trigger the SelectedIndexChanged event for the DropDownList as
<asp:AsyncPostBackTrigger ControlID="DropDownList" EventName="SelectedIndexChanged" />
You just need to trigger a valid event in the code behind.
Update: Since the SelectedIndexChanged updates the database, so you need to refresh the DataGrid to populate the updated data.
Add this line code at the end of SelectedIndexChanged method:
GridView2.DataBind();
use ajax update panel this may help http://ajax.net-tutorials.com/controls/updatepanel-control/

How to let this DropDownList (filter) works again with this GridView?

I am developing an intranet web application which works as a Suggstions Box. The Admin will see a list of all submitted suggestions in a GridView and he has the ability to accept or reject these suggestions through the DropDownList that is added to the GridView. Besides that, there is a DropDownList at the top of this GridView to filter the suggestions based on the Division of the user who submitted one of these suggestions.
In addition, under this GridView, there is another GridView that shows the suggestions with their status as Accepted or Rejected. This GridView will be refreshed immediately after each time the admin accepts or rejects one of the suggestions. Also, the Admin has the ability to print this GridView.
Everything was working fine before adding the second GridView inside the UpdatePanel control, but now the filter for filtering the suggestions in the first GridView is not working. Any idea? Any help please?
My ASP.NET Code:
<strong> Division </strong>
<asp:DropDownList ID="ddlDivision" runat="server" AppendDataBoundItems="True"
AutoPostBack="True" DataSourceID="sqlDataSourceDivision" DataTextField="DivisionShortcut"
DataValueField="DivisionShortcut"
Width="175px" EnableViewState="False">
<asp:ListItem Value="%">All</asp:ListItem>
</asp:DropDownList>
<br /> <br />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID"
width="950px" CssClass="mGrid"
AlternatingRowStyle-CssClass="alt"
RowStyle-HorizontalAlign="Center"
DataSourceID="SqlDataSource1"
OnRowDataBound="GridView1_RowDataBound" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<HeaderStyle Font-Bold = "true" ForeColor="Black" Height="20px"/>
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" />
<asp:BoundField DataField="DivisionShortcut" HeaderText="Division"
SortExpression="DivisionShortcut" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="DropDownList" runat="server" DataSourceID="SqlDataSource2"
Font-Bold="True" ForeColor="#006666" AppendDataBoundItems="false"
DataTextField="Status" DataValueField="ID" AutoPostBack="true"
OnDataBound="DropDownList_DataBound" OnSelectedIndexChanged ="DropDownList_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT dbo.SafetySuggestionsLog.ID, dbo.SafetySuggestionsLog.Title, dbo.SafetySuggestionsLog.Description, dbo.employee.Name, dbo.SafetySuggestionsLog.Username,
dbo.Divisions.DivisionShortcut
FROM dbo.employee INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username INNER JOIN
dbo.Divisions ON dbo.employee.DivisionCode = dbo.Divisions.SapCode"
FilterExpression="[DivisionShortcut] like '{0}%'">
<FilterParameters>
<asp:ControlParameter ControlID="ddlDivision" Name="DivisionShortcut"
PropertyName="SelectedValue" Type="String" />
</FilterParameters>
</asp:SqlDataSource>
<%--For the DropDownList--%>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT * FROM [SafetySuggestionsStatus]">
</asp:SqlDataSource>
<%--Filtering by Division--%>
<asp:SqlDataSource ID="sqlDataSourceDivision" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT [DivisionShortcut] FROM [Divisions]"></asp:SqlDataSource>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlDivision" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<br />
<p><h3><b><u>PMOD Divisions' Safety Suggestions List</u></b></h3>
<p>
</p>
<br />
<asp:Panel ID="Panel1" runat="server">
<asp:GridView ID="GridView2" runat="server" AllowSorting="True"
AlternatingRowStyle-CssClass="alt" AutoGenerateColumns="False" CssClass="mGrid"
DataSourceID="SqlDataSource4" RowStyle-HorizontalAlign="Center">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<HeaderStyle Font-Bold="true" ForeColor="Black" Height="20px" />
<Columns>
<asp:BoundField DataField="SubmittedMonth" HeaderText="Month Submitted"
ReadOnly="True" SortExpression="SubmittedMonth" />
<asp:BoundField DataField="DivisionShortcut" HeaderText="Division"
SortExpression="DivisionShortcut" />
<asp:BoundField DataField="Username" HeaderText="NetworkID"
SortExpression="Username" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
</Columns>
<RowStyle HorizontalAlign="Center" />
</asp:GridView>
</asp:Panel>
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>" SelectCommand="SELECT TOP (100) PERCENT LEFT(DATENAME(month, dbo.SafetySuggestionsLog.DateSubmitted), 3) + '-' + DATENAME(year, dbo.SafetySuggestionsLog.DateSubmitted)
AS SubmittedMonth, dbo.Divisions.DivisionShortcut, dbo.SafetySuggestionsLog.Username, dbo.employee.Name, dbo.SafetySuggestionsLog.Title,
dbo.SafetySuggestionsLog.Description, dbo.SafetySuggestionsType.Type, dbo.SafetySuggestionsStatus.Status
FROM dbo.Divisions INNER JOIN
dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username INNER JOIN
dbo.SafetySuggestionsType ON dbo.SafetySuggestionsLog.TypeID = dbo.SafetySuggestionsType.ID INNER JOIN
dbo.SafetySuggestionsStatus ON dbo.SafetySuggestionsLog.StatusID = dbo.SafetySuggestionsStatus.ID
WHERE (DATEDIFF(month, dbo.SafetySuggestionsLog.DateSubmitted, GETDATE()) < 3)
ORDER BY dbo.SafetySuggestionsLog.DateSubmitted DESC"></asp:SqlDataSource>
<asp:Button ID="btnPrint" runat="server" OnClick="btnPrint_Click"
Text="Print" />
<p>
</p>
</p>
</ContentTemplate>
</asp:UpdatePanel>
Code-Behind:
protected void btnPrint_Click(object sender, EventArgs e)
{
Session["ctrl"] = Panel1;
ScriptManager.RegisterStartupScript(GridView2, GridView2.GetType(), "onclick", "window.open('Print.aspx','PrintMe','height=400px,width=800px,scrollbars=1');", true);
}
int i = 1;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Text = i.ToString();
i++;
}
}
protected void DropDownList_DataBound(object sender, EventArgs e)
{
if (!IsPostBack)
{
((DropDownList)sender).Items.Insert(0, new ListItem("--Select--", ""));
}
}
protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
int suggestionStatus = int.Parse(ddl.SelectedValue);
GridViewRow row = (GridViewRow)ddl.NamingContainer;
string strID = GridView1.DataKeys[row.RowIndex]["ID"].ToString();
int ID = Int32.Parse(strID);
//For inserting the status in the database
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdbTest;Integrated Security=True";
string updateCommand = "UPDATE SafetySuggestionsLog SET [StatusID] = #StatusID WHERE [ID] = #ID";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(updateCommand, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#StatusID", suggestionStatus);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.ExecuteNonQuery();
}
conn.Close();
}
GridView2.DataBind();
}
Can you specify what is the id for the 1st grid?
What I can conceive is that maybe you are not updating the updatepanel manually on your selectedIndex change event
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(updateCommand, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#StatusID", suggestionStatus);
cmd.Parameters.AddWithValue("#ID", ID);
conn.Open();
cmd.ExecuteNonQuery();
}
conn.Close();
}
GridView2.DataBind();
UpdatePanel1.Update();
Also in your aspx set UpdateMode="Conditional"
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">

Value from row with DropDownList on DropDownList Index Changed Event

Code:
<asp:GridView ID="gv_Recruit" AutoGenerateColumns="False" Width="100%"
runat="server" OnRowCreated="gvStates_RowCreated"
OnRowDataBound="gvStates_RowCreated">
<Columns>
<asp:BoundField HeaderText="key" DataField="key" />
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Quota" DataField="Quota" />
<asp:BoundField HeaderText="Session" DataField="Sess" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:DropDownList ID="ddlCities" Width="100%" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddl_selected">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Recruiter" DataField="Recruiter" />
<asp:BoundField HeaderText="MN Phone" DataField="MN Phone" />
<asp:BoundField HeaderText="Cell Phone" DataField="Cell Phone" />
</Columns>
</asp:GridView>
Code Behind:
protected void ddl_selected(object sender, EventArgs e)
{
string _dd_value = ((DropDownList)sender).SelectedValue;
string trying_to_get = gv_Recruit.Rows[???].Cells[0].Text.ToString();
string also_tried = gv_Recruit.SelectedRow.Cells[0].Text.ToString();
}
Basically what I'm trying to do is get the key value from the first row when the drop down is changed so I can perform an update ???
Can't figure this out.
Thanks in advance for the help...
Try
GridViewRow gRow = (GridViewRow)(sender as Control).Parent.Parent;
string trying_to_get = string.Empty;
if (gRow != null)
{
trying_to_get = gRow.Cells[0].Text;
}

Categories

Resources