Enable/Disable button on Gridview per row - c#

I have a GridView that has a Like and a Dislike Button in each Row.
What I want to do is for the user to be able to click only one of those per Row and Enable or Disable that Button per row when that particular Button is clicked.
I have a Sql Table tblVote that has a Field with the Name Vote. This Keeps a tally for the user if they have voted for that item. If the user clicks the Dislike Button for the first record it will write a 0 to the Vote Column under itemId 1. If user clicks on Like it will write a 1 and so on for each record. I have this part working already. How can I read from the table and issue that Button that state depending on the value on the Vote Field on tblVote.
Table:
ItemId | UserID | Vote
1 | 123 | 0
2 | 123 | 1
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" AutoGenerateColumns="False" DataKeyNames="SwotItemID" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource1" OnRowCommand="GridViewStrength_RowCommand"
Width="100%" onrowdatabound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="ItemDesc" HeaderText="Item Description" SortExpression="ItemDesc">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField HeaderText="Like" InsertVisible="False" SortExpression="Vote">
<ItemTemplate>
<asp:Button ID="Btn_thumbs_up" runat="server" Text = "Like"
CommandName="VoteUp" CommandArgument='<%# Bind("SwotItemID") %>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Dislike" InsertVisible="False" SortExpression="Vote">
<ItemTemplate>
<asp:Button ID="Btn_thumbs_down" runat="server" Text = "Dislike"
CommandName="VoteDown" CommandArgument='<%# Bind("SwotItemID") %>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>

I think you should be able to do this with a foreach loop. You can do something like..
string vote;
//Your connection string. You don't want to open and close within the foreach because it will open and close for each row. Not ideal
conn.Open();
foreach(GridViewRow gvr in GridView1.Rows)
{
//you'll want to find the buttons
Button voteUp = ((Button)gvr.FindControl("Btn_thumbs_up"));
Button voteDown = ((Button)gvr.FindControl("Btn_thumbs_down"));
Label SwotItemID = ((Label)gvr.FindControl("SwotItemID));//I would add SwotItemID as a templatefield with an asp label in it in your gridview
SqlCommand cmdSelectVote= new SqlCommand("SELECT ThumpUpColumn FROM tLoveOrHateTable WHERE SwotItemID = '" + SwotItemID + "'", conn);
vote = Convert.ToString(cmdSelectVote.ExecuteScalar());
if(vote == "0")
{
voteDown.Enabled = false;
}
else if (vote == "1")
{
voteUp.Enabled = true;
}
}
conn.Close();
I would have then on page load or a button or something. Whatever populates your data. This is what I would try first then go from there. So what's it is doing it is running that sql statement for each row. If it's a 0, then it disables the thumbs down button. If it is a 1 then it will disable the thumbs up button. It will go row by row, so if you have 1000 rows(I don't imagine that you do) then it could slow things down. Don't hold me that it will work right away as I have not tested it and I wrote it with in the box. Hope this helps!

Related

Unable to get data from TextBox/DDL in Gridview

I have been looking all over web and testing what I think would work. I feel close but I guess not close enough. I need help pull the data in. The button click is to submit/insert data into the DB which I have not completed that part. Right now I am working on just getting data from the Gridview and need help.
The Update Button is outside the Gridview. I want end user to complete GridView then click update to submit data from Gridview to database.
Here is ASPX
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="dsSnumbers" OnRowDataBound="GridView1_RowDataBound"
GridLines="Horizontal" BackColor="White" BorderColor="#336666" BorderStyle="Double"
BorderWidth="3px">
<Columns>
<asp:TemplateField HeaderText="SerialNumber">
<ItemTemplate>
<asp:TextBox ID="TextBox1" BackColor="BurlyWood" runat="server" Text='<%# Eval("SerialNumber") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="DdStatus" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dept">
<ItemTemplate>
<asp:DropDownList ID="DdDept" runat="server" DataSourceID="Ds_Variables" DataTextField="Status" DataValueField="Value" Height="16px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Update">
<ItemTemplate>
<asp:CheckBoxList ID="CheckBoxList1" RepeatLayout="Flow" RepeatDirection="Horizontal"
runat="server">
<asp:ListItem Text="Modify?" Value="1">
</asp:ListItem>
</asp:CheckBoxList>
<br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#333333" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
<%-- <EmptyDataTemplate></EmptyDataTemplate>--%>
</asp:GridView>
And here is the .CS side
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
int RI = g1.RowIndex;
//SqlConnection con = new SqlConnection(connStr);
TextBox test = (TextBox)g1.Cells[0].FindControl("TextBox1");
TextBox test1 = (TextBox)g1.Cells[1].FindControl("TextBox1");
GridViewRow Grow = (GridViewRow)g1.NamingContainer;
TextBox txtledName = (TextBox)Grow.FindControl("TextBox1");
DropDownList testdd1 = (DropDownList)g1.Cells[0].FindControl("DdStatus");
DropDownList testdd2 = (DropDownList)g1.Cells[1].FindControl("DdStatus");
string test1324 = g1.Cells[1].Text;
string test2 = g1.Cells[2].Text;
string test3 = g1.Cells[3].Text;
}
}
Update:
When I run the below I can read the button click whether it is checked or not. However the textbox and dropdown still do nothing. I show ONLY rindex is pulling values. None of the others.
foreach (GridViewRow row in GridView1.Rows)
{
int rindex = row.DataItemIndex;
//string Test = ((TextBox)(row.Cells[0].Controls[0])).Text;
TextBox IDNum = (TextBox)row.FindControl("TextBox1");
string textBox1 = ((TextBox)row.FindControl("TextBox1")).Text;
string ddl1 = ((DropDownList)row.FindControl("DdStatus")).SelectedValue;
string ddl2 = ((DropDownList)row.FindControl("DdDept")).SelectedValue;
int ddl1231 = ((DropDownList)row.FindControl("DdStatus")).SelectedIndex;
int ddl1232 = ((DropDownList)row.FindControl("DdDept")).SelectedIndex;

Adding record to sql with gridview rowcommand buttonfield

I'm trying to add a Register button to every row in my course gridview so that when the user click on the register button on that particular row, it will register him to that particular course on that row by adding a course registration record into sql.
How should I write my code to insert that row's data into sql?
C#:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Register")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
}
ASP.NET:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
OnRowCommand="GridView1_RowCommand" Width="394px">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Title" HeaderText="Title" ReadOnly="True"></asp:BoundField>
<asp:BoundField DataField="SpeakerName" HeaderText="Speaker" ReadOnly="True" />
<asp:BoundField DataField="startdate" HeaderText="Date" ReadOnly="True" />
<asp:BoundField DataField="Capacity" HeaderText="Capacity" />
<asp:TemplateField HeaderText="Button" ShowHeader="False">
<ItemTemplate>
<asp:Button ID="RegButton" runat="server" CausesValidation="false" CommandName="Register"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="Register" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Select" SelectText="Details" ShowSelectButton="True" />
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
first you should add course Id (primary key) as datakeynames property to GridView1,and then can get the Id on GridView1_RowCommand like below :
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Register")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).NamingContainer;
int courseId = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
//your other codes
}
so,you have your course Id and by selecting the record you can add current record to sql.hope it helps.
Edit :
also you don't need this part CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" in your aspx page any more

Gridview empty rows issue

I'm using the below code to add a new row to a ASP.net gridview. The problem is that every new row I create is blank. I looped through the cells in the row and found that most of them were spaces ( ). I've looked everywhere for a different piece of code to use, but everything leads me to: create a new datatable, add a row to it, set the gridview datasource to the datatable. I've used this control a dozen times before and never got this before, it's very odd.
Class Level Variable
public partial class DMREntry : System.Web.UI.Page
{
private DataTable _Parts
{
get { return (DataTable)ViewState["Parts"]; }
set { ViewState.Add("Parts", value); }
}
...
The add row code. Note that my textboxes and my gridview are within an update panel.
if (_Parts == null)
{
_Parts = new DataTable();
_Parts.Columns.Add("Part No");
_Parts.Columns.Add("Qty");
_Parts.Columns.Add("Description");
_Parts.Columns.Add("Vendor");
_Parts.Columns.Add("Vendor Part");
_Parts.Columns.Add("Cost");
_Parts.Columns.Add("PO Number");
_Parts.Columns.Add("Delivery Date");
_Parts.Columns.Add("Total Cost");
}
DataRow dr = _Parts.NewRow();
dr["Part No"] = txtPartNo.Text;
dr["Qty"] = txtQty.Text;
dr["Description"] = txtDescription.Text;
dr["Vendor"] = txtVendor.Text;
dr["Vendor Part"] = txtVendorPart.Text;
dr["Cost"] = txtCost.Text;
dr["PO Number"] = txtPONumber.Text;
dr["Delivery Date"] = txtDeliveryDate.Text;
dr["Total Cost"] = txtTotalCost.Text;
// At this point, DR has the correct values
_Parts.Rows.Add(dr);
_Parts.AcceptChanges();
gvParts.DataSource = _Parts;
gvParts.DataBind();
upGrid.Update();
GridView markup:
`<asp:GridView ID="gvParts" runat="server" AutoGenerateColumns="False" PageSize="5"
Width="787px" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None"
BorderWidth="1px" CellPadding="3"
onselectedindexchanged="gvParts_SelectedIndexChanged1" AllowPaging="True"
AllowSorting="True">
<Columns>
<asp:TemplateField HeaderText="Part No"></asp:TemplateField>
<asp:TemplateField HeaderText="Qty"></asp:TemplateField>
<asp:TemplateField HeaderText="Description"></asp:TemplateField>
<asp:TemplateField HeaderText="Vendor"></asp:TemplateField>
<asp:TemplateField HeaderText="Vendor Part"></asp:TemplateField>
<asp:TemplateField HeaderText="Cost"></asp:TemplateField>
<asp:TemplateField HeaderText="PO Number"></asp:TemplateField>
<asp:TemplateField HeaderText="Delivery Date"></asp:TemplateField>
<asp:TemplateField HeaderText="Total Cost"></asp:TemplateField>
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
<asp:CommandField ButtonType="Button" ShowDeleteButton="True" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>`
Leaves me with:
My grid properties are the default, except:
AutoGenerateColumns = false
AllowPaging = true
AllowSorting = true
PageSize = 5
If I turn AutoGenerateColumns on, the data from the table does go into the auto-generated columns. But not for when I create the columns manually. I am using the template field column type for the manually added columns. They're just text fields, I couldn't find a better option.
Any help appreciated...
Why you are using asp:TemplateField ? You did not add any control in the templatefield.
Just change TemplateField to BoundField then it will solve your problem.
Like:
<asp:BoundField DataField="Part No" HeaderText="Part No" />
<asp:BoundField DataField="Qty" HeaderText="Qty" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="Vendor" HeaderText="Vendor" />
<asp:BoundField DataField="Vendor Part" HeaderText="Vendor Part" />
<asp:BoundField DataField="Cost" HeaderText="Cost" />
<asp:BoundField DataField="PO Number" HeaderText="PO Number" />
<asp:BoundField DataField="Delivery Date" HeaderText="Delivery Date" />
<asp:BoundField DataField="Total Cost" HeaderText="Total Cost" />
Try creating inside the an tag
<asp:TemplateField HeaderText="Example">
<ItemTemplate>
<%# Eval("TestColumn") %>
</ItemTemplate>
</asp:TemplateField>

How do I get value of field in nested gridview where checkbox is checked?

I have a nested gridview inside another gridview. The parent gridview has a list of tasks, and each task has a list of steps (the child gridview). Each step has a checkbox so once a user is done with a step, he'll check the checkbox and that will fire the CheckChanged event in which I have a stored procedure to update the database so the checked step registers as completed.
I have a CheckChanged event that looks for the step ID of the row the checked checkbox was in, then fires off the stored procedure using the step ID as an input parameter. This works. However, steps can be added, and for some reason, when a check box on an earlier step is clicked, the code that looks for the step ID won't go backwards and recognize the step ID. In other words, if a if the the step ID of a certain task is 20, and it is checked and the event fires off, if I add a step to an earlier task (a task listed higher on the gridview) and that step has an ID of 21, clicking on it will constantly register the step ID as 20, as if the CheckChanged event doesn't recognize a step added to another task. Here is my code:
aspx:
<asp:GridView ID="GridView1"
DataKeyNames="TaskID"
runat="server"
OnRowDataBound="GridView1_OnRowDataBound"
CssClass="DefaultGrid"
onRowCommand="GridView1_RowCommand"
EmptyDataText = "<br/>There are no Tasks in this Project."
AllowPaging="True"
AllowSorting="True"
CellPadding="4"
DataSourceID="SqlDataSource_mp_Display_Tasks_Home"
ForeColor="#333333"
GridLines="None"
AutoGenerateColumns="False">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<RowStyle CssClass=" table-responsive body-content " />
<Columns>
<asp:CommandField ShowSelectButton="False" />
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="Images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display:none">
<asp:GridView ID="GridView2"
runat="server"
onRowCommand="GridView2_RowCommand"
Datakeynames="TaskStepID"
CssClass="ChildGrid"
EmptyDataText="<br/>There are no Steps in this Task."
AutoGenerateColumns="false"
onselectedindexchanged="GridView2_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="TaskStepID" HeaderText="TaskStepID" Visible="true" />
<asp:BoundField DataField="TaskID" HeaderText="TaskID" Visible="false" />
<asp:BoundField DataField="TaskStepTypeID" HeaderText="TaskStepTypeID" Visible="false"/>
<asp:BoundField DataField="TaskStepPriority" HeaderText="Task Step Priority" Visible="false" />
<asp:BoundField ItemStyle-Width="70%" DataField="TaskStepDesc" HeaderText="Step Description" />
<asp:TemplateField HeaderText="Step Completed" ItemStyle-Width="15%" >
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Checkbox ID="TaskStepCompleted"
OnCheckedChanged="TaskStepCompleted_CheckedChanged"
Checked='<%# Eval("TaskStepCompleted") %>'
runat="server"
AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TaskStepComment" HeaderText="TaskStepComment" Visible="false" />
<asp:TemplateField HeaderText="Step Activity" ItemStyle-Width="15%">
<ItemTemplate>
<asp:LinkButton Text="Add" ID="Addstep" runat="server" CommandName="addstep" CommandArgument='<%# Eval("TaskStepID") %>'/>
<asp:LinkButton Text="Edit" ID="Editstep" runat="server" CommandName="editstep" CommandArgument='<%# Eval("TaskStepID") %>'/>
<asp:LinkButton Text="Delete" ID="Deletestep" runat="server" CommandName="deletestep" OnClientClick="return confirm('<%=AlertMe%>');" CommandArgument='<%# Eval("TaskStepID") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TaskID" HeaderText="Task ID" Visible="false"/>
<asp:BoundField DataField="ProjectID" HeaderText="Project ID" Visible="false" />
<asp:BoundField DataField="TaskTypeID" HeaderText="Task Type ID" Visible="false" />
<asp:BoundField DataField="TaskCompleted" HeaderText="Taske Completed?" Visible="false" />
<asp:BoundField DataField="TaskCreationDate" HeaderText="Task Creation Date" Visible="false" />
<asp:BoundField DataField="TaskSubmitterID" HeaderText="Task Submitter ID" Visible="false" />
<asp:BoundField DataField="DepartmentID" HeaderText="DepartmentID" Visible="false" />
<asp:BoundField DataField="TaskDueDateCommentType" HeaderText="Due Date Comment" Visible="false" />
<asp:BoundField DataField="TaskLastUpdatedDate" HeaderText="Task Last Updated Date" Visible="false" />
<asp:BoundField DataField="TaskLastUpdatedUserID" HeaderText="Task Last Updated UserID" Visible="false" />
<asp:BoundField DataField ="TaskSubmitterName" HeaderText="Task Submitter Name" Visible="false" />
<asp:BoundField DataField="TaskLastUpdatedUser" HeaderText="Task Last Updated User" Visible="false" />
<asp:BoundField DataField="DepartmentDesc" HeaderText="Dept" visible="false"/>
<asp:TemplateField HeaderText="Task Description">
<ItemTemplate>
<asp:Label ID="TaskDescription" runat="server" Text='<%# HighlightText(Eval("TaskDescription").ToString()) %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="40%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="% Comp.">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="PercentCompleted" runat="server" Text='<%# (String.IsNullOrEmpty(Eval("PercentCompleted").ToString()) ? "0" : Eval("PercentCompleted")) + " %" %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TaskDueDate" HeaderStyle-HorizontalAlign="Right" HeaderText="Task Due Date" DataFormatString="{0:MM-dd-yyyy}" visible="true"/>
<asp:BoundField DataField="TaskTypeName" HeaderText="Task Type" visible="true" />
<asp:BoundField DataField="DepartmentAbbrev" HeaderText="Dept" Visible="true" />
<asp:TemplateField HeaderText="Activity">
<ItemTemplate>
<asp:LinkButton Text="Edit" ID="Edittask" runat="server" CommandName="edittask" CommandArgument='<%# Eval("TaskID") %>'/>
<asp:LinkButton Text="Delete" ID="Deletetask" runat="server" CommandName="deletetask" OnClientClick="return confirm('Are you sure you wish to Delete this Task?');" CommandArgument='<%# Eval("TaskID") %>'/>
<asp:LinkButton Text="Comments" ID="Detailstask" runat="server" CommandName="detailstask" CommandArgument='<%# Eval("TaskID") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource_mp_Display_Tasks_Home" runat="server" FilterExpression="TaskDescription LIKE '%{0}%'" ConnectionString="<%$ ConnectionStrings:IntelliBaseConnectionString_mp_Display_Projects_Home %>" SelectCommand="mp_Display_Tasks_Home" SelectCommandType="StoredProcedure" ProviderName="System.Data.SqlClient">
<SelectParameters>
<asp:Parameter Name="Incoming_ProjectID" Type="Int32" />
</SelectParameters>
<FilterParameters>
<asp:ControlParameter Name="TaskDescription" ControlID="txtSearchtasks" PropertyName="Text"/>
</FilterParameters>
</asp:SqlDataSource>
cs:
protected void TaskStepCompleted_CheckedChanged(object sender, EventArgs e)
{
// this nested foreach grabs the taskstepID number for the row in which the checkbox was just checked.
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
GridView GridView2 = (GridView)row.FindControl("GridView2");
if (GridView2 != null)
{
foreach (GridViewRow Row in GridView2.Rows)
{
if (Row.RowType == DataControlRowType.DataRow)
{
System.Web.UI.WebControls.CheckBox chk = (System.Web.UI.WebControls.CheckBox)Row.FindControl("TaskStepCompleted");
if (chk.Checked || !chk.Checked)
{
Session["TaskStepID"] = GridView2.DataKeys[Row.RowIndex]["TaskStepID"].ToString();
}
}
}
}
}
}
// autopost back the check box to run the stored procedure
var TaskStepID = Session["TaskStepID"].ToString();
var ProjectID = Session["ProjectID"].ToString();
using (var conn = new SqlConnection("Data Source=orlandosql1;Initial Catalog=IntelliBase;Persist Security Info=True;User ID=trainingsurveys_webuser;Password=C#mb3rSQL;"))
using (SqlCommand cmd = new SqlCommand("dbo.mp_Task_Step_Completed_Toggle", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#TaskStepID", SqlDbType.Int).Value = TaskStepID;
cmd.Parameters.Add("#AdminUserID", SqlDbType.Int).Value = "10";
cmd.Parameters.Add("#LogActionItemID", SqlDbType.Int).Value = "15";
cmd.Parameters.AddWithValue("#DTStamp", SqlDbType.DateTime.ToString("d")).Value = DateTime.Now.ToString("d");
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect("Tasks.aspx?id=" + ProjectID.ToString());
}
}
I tried my best to describe the issue. To recap: nested gridview has rows with check boxes. Clicking the checkbox automatically updates db tables, but regardless of check box row, the CheckedChanged code will only register the ID of the most recent ID. Any insight is appreciated.
Carlos
If I understand correctly, I believe your issue comes with how you think you are grabbing the TaskStepID of your GridViewRow. You are doing a lot of unnecessary work. Instead of iterating every row of both GridViews, just grab the GridViewRow of the CheckBox that was just clicked.
CheckBox cb = (CheckBox)sender;
GridViewRow row = (GridViewRow)cb.NamingContainer;
GridView gv = (GridView)row.NamingContainer;
string taskStepID = gv.DataKeys[row.RowIndex].Value.ToString();
Notice how by iterating each row like you were, you were always getting the TaskStepID of the last row. So when you added a row before it, it was using the last row instead of the one you expected.

Template field column got removed when we remove any column from gridview

I have a gridview control on my web form with 1 template field column.
And i am adding some bounded columns at run time from code behind.
And some times I've removed some of the previously added columns from code behind.
After removing any column gridview losses template column.
What is the cause behind this and how can i prevent template column with out setting EnableViewState="false".
Edit-1
.aspx page Code
<asp:GridView ID="grvSum" runat="server" Width="100%" GridLines="None" AllowPaging="True" ShowFooter="true"
PageSize="25" CellPadding="4" ForeColor="#333333" AutoGenerateColumns="false" AllowSorting="true" EnableViewState="false"
OnRowUpdating="grvSum_RowUpdating" OnPageIndexChanging="grvSum_PageIndexChanging" OnSorting="grvSum_Sorting"
OnRowDataBound="grvSum_RowDataBound" Font-Size="10px">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:LinkButton ID="dtype" runat="server" CommandName="update"
CssClass="lbl" Font-Underline="true" style="cursor:pointer;" Text="Details" >
</asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="20px"/>
<FooterTemplate>
<asp:Label ID="lblFooter" runat="server" Text="Total"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" HorizontalAlign="Center"/>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" HorizontalAlign="Center"/>
<HeaderStyle HorizontalAlign="Center" BackColor="#507CD1" Font-Bold="True" ForeColor="White" Height="30px" Wrap="true"/>
<PagerStyle HorizontalAlign="Right" CssClass="GridPager" />
<RowStyle BackColor="#EFF3FB" HorizontalAlign="Center"/>
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" CssClass="headerSortUp" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" CssClass="headerSortDown"/>
</asp:GridView>
Code for adding and removal of column
public void AddBoundedColumns(GridView grv, DataColumnCollection dtDataSourceColumns)
{
var gridBoundColumns = grv.Columns.OfType<BoundField>();
foreach (DataColumn col in dtDataSourceColumns)
{
//Check existence of column in gridview
if (gridBoundColumns.Any(bf => bf.DataField.Equals(col.ColumnName)) == false)
{
//Declare the bound field and allocate memory for the bound field.
BoundField bfield = new BoundField();
//Initalize the DataField value.
bfield.DataField = col.ColumnName;
//Initialize the HeaderText field value.
bfield.HeaderText = col.ColumnName;
bfield.SortExpression = col.ColumnName;
//Add the newly created bound field to the GridView.
grv.Columns.Add(bfield);
}
}
gridBoundColumns = grv.Columns.OfType<BoundField>();
int z = 0;
for (int x = 0; x < gridBoundColumns.Count(); x++)
{
BoundField c = gridBoundColumns.ElementAt(z);
if (!dtDataSourceColumns.Contains(c.HeaderText))
{
grv.Columns.Remove(c);
}
else
{
z++;
}
}
}
instead of grv.Columns.Remove(c);, try following while removing the column
grv.columns.RemoveAt(index); //"index" is the index of column you want to remove

Categories

Resources