GridViewRow FindControl query C# - c#

I am building a simple C# web app which will act like an online database for resources.
In my table, I have a category and author column.
When I click a category value in the table, the table will refresh showing only the categories that was selected.
To do this I used the following code:
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label category = (Label)clickedRow.FindControl("lbl_category");
String selectedCategory = category.Text.ToString();
string query =
("SELECT * FROM main WHERE category='" + selectedCategory + "' ORDER BY ID ASC");
This works fine for the first time I click a category/author. But after the table has refreshed, and select another category or author then the table shows the wrong record.
How can I solve this?
You can view the page here: Try clicking at category 'Health' and then 'Puvent, Kevin'. The outcome is different to the one that was expected. I think
The question will probably make more sense once you see the page :)
EDIT - This is the gridview binding code:
<asp:TemplateField HeaderText="Category" ItemStyle-Width="15%">
<ItemTemplate>
<asp:Label ID="lbl_category" Text='<%# Bind("category")%>' runat="server" style="display:none;"></asp:Label>
<asp:LinkButton ID="lbl_linkCategory" Text='<%# Bind("category")%>' runat="server" OnClick="linkCategory" CommandArgument='<%# Bind("category")%>' />
</ItemTemplate>
</asp:TemplateField>

When you click on a category this changes the controls underneath. The control numbers changes. You reference that number and it is wrong, it needs to be constant and an ID of the table "main". You will have to find a way to assign the corresponding number to selectedCategory properly. You could do that by adding an attribute to the category-label, or check on what has been clicked. Like Finance => selectedCategory = 2, Health = 3, Family = 4 etc. Hopes it helps.

Using if (!IsPostBack) in Page_Load seemed to have solved the problem :)

Related

Value of HiddenField Duplicated when called from Nested Gridvew Row Editing

Problem: I'm trying to get a value from a HiddenField object and set it to a string. A value of "foo" is being returned as "foo, foo".
Details:
I have a Nested Gridview, and I'm trying to make the child Gridview editable. I have a method GetChildQuery(string id) which form the sql query to get the data for the Child Gridview, and I have the id bound to a HiddenField object in the HTML as so:
<asp:Gridview ID="gvChild" runat="server" AutoGenerateColumns="false" OnRowEditing = "gvChild_RowEditing">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label runat="server" ID="lblNameChild" Text='<% Eval("Name")%>'></asp:Label>
<asp:HiddenField runat="server" ID="hidIDChild" Value ='<%# Bind("ItemID") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:Label runat="server" ID="lblNameChildEdit" Text='<% Eval("Name")%>'></asp:Label>
<asp:HiddenField runat="server" ID="hidIDChildEdit" Value ='<%# Bind("ItemID") %>' />
</EditItemTemplate>
</asp:TemplateField>
and I try to access it in the OnRowEditing method like:
protected void gvhild_RowEditing(object sender, GridViewEditEventArgs e) {
Gridview child = sender as Gridview;
string itemID = (child.Rows[e.NewEditIndex].FindControl("hidIDChild") as HiddenField).Value.ToString();
string sql = GetChildQuery(itemID);
child.EditIndex = e.NewEditIndex;
child.DataSource = GetData(sql);
child.DataBind();
}
The id is used in the WHERE clause of my SQL query, and therefore the output is incorrect if the value of the id is incorrect. I don't know I this problem is occurring because of how I bind data to the HiddenField or how I'm calling it from the RowEditing method, or something I'm completely overlooking.
Ref: To make the Nested Gridview, I mainly followed https://www.aspsnippets.com/Articles/Nested-GridView-Example-in-ASPNet-using-C-and-VBNet.aspx and https://www.aspforums.net/Threads/133072/Edit-Update-Delete-in-Nested-Child-GridView-in-ASPNet/ which has the general format for my GetData method as well.
EDIT: Problem subverted by replacing the string itemID instantiation to
string itemID= ((child.Rows[e.NewEditIndex].FindControl("hidIDChild") as HiddenField).Value.Split(','))[0].ToString();
essentially splitting the duplication, accessing the first element, converting that to a string, and setting that equal to y string itemID.
However while this subverts the problem, I would still appreciate anyone's feedback as to why the problem is occurring in the first place. Thanks!
You should look at your rendered html.
When dealing with one gridview there is only ever one row open for editing at a time. And within a row's TemplateField the ItemTemplate and EditTemplate are mutually exclusive, that is to say that, when rendered, you will see only one or the other.
Likewise in the code behind, you will only have access to either the ItemTemplate row or the EditTemplate row depending on which event you process on postback.
The same rules apply to a nested/child Gridview.
So for the case you describe, I assume you are trying to use some ID from the parent to build a query to populate the child. If so I do not believe you need any hidden fields at all. This ID fieldname from the parents query should be set in the DataKeyNames property of the parent gridview.
You should then be able to pass the value to the procedure you are building for the child as
protected void gvhild_RowEditing(object sender, GridViewEditEventArgs e) {
string sql = GetChildQuery(gvParent.SelectedDataKey.Value);
child.DataSource = GetData(sql);
child.DataBind();
// Given that you have just populated the child I do not think the
// following is accurate, but that's for you to decide
child.SetEditRow(e.NewEditIndex);
}
Hope this helps.

Getting the value of a Textbox in a TemplateField in a gridview

i'm gonna keep it short and simple
I'm a software engineering student in the 12th grade and as my final project I have decided to make a website. What the website is about doesn't really matter. The problem is this:
In the picture attached there is a textbox inside a templatefield inside that gridview. I need to get the value that the user writes inside. After you write a value you press Purchase. I've looked at similar questions and none offered a working solution. What happens is the value just disappears. I find the right control with FindControl, but the value gets deleted somehow. How do I know I am at the right control? I went to the client side and added to the asp:TextBox the following:
Text="5"
This works perfectly, so I know it gets to the right control but something makes it disappear. My gridview is being populated by a DataSet that is two datasets combined, and I put the Merge command and the DataSource and DataBind are both in if (!this.IsPostBack). I am completely lost and have no idea what to do, Help is much appreciated.The Picture of the Gridview
All the controls in a GridView are accessible by searching the correct row with FindControl. For that you can send the row number as a CommandArgument and use that in code behind. So first start by using OnCommand instead on OnClick and set the CommandArgument on the aspx page.
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Purchase" OnCommand="Button1_Command" CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
And then in code behind
protected void Button1_Command(object sender, CommandEventArgs e)
{
//get the rownumber from the command argument
int rowIndex = Convert.ToInt32(e.CommandArgument);
//find the textbox in the corrext row with findcontrol
TextBox tb = GridView1.Rows[rowIndex].FindControl("TextBox1") as TextBox;
//get the value from the textbox
try
{
int numberOfTickets = Convert.ToInt32(tb.Text);
}
catch
{
//textbox is empty or not a number
}
}

How to not get repeated values with gridview?

i have a gridview to insert values to the database dynamically..
i have one dropdownlist for selecting employee id and one textbox for getting personnel details...
dropdownlist values are getting from database using select query and binding those values into dropdownlist which exists in gridview
personnel details text box values entered by user for each employee
if one employee selects from dropdownlist and inserts details into textbox after submitting his details his empid must hide in that dropdownlist...for not getting multiple rows about the employee.
<asp:TemplateField HeaderText="EMPID>
<ItemTemplate>
<asp:DropDownList ID="empid" runat="server" Width="100px">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EMPID>
<ItemTemplate>
<asp:TextBox id="txtbox" runat="server" width="100px"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="Add_Details" runat="server" Text="Add Details" OnClick="Addhour_Click"/>
</FooterTemplate>
</asp:TemplateField>
in the above empid is the dropdownlist which binds data from database...
and txtbox is used to get the personneldetails about the empid selected from dropdownlist empid...
after selecting one id from dropdownlist and entering some data into text if we click to add details button the details are storing into database correctly and inserting another row into gridview..
but again already inserted empid also displaying in that dropdownlist...
how to remove that item from dropdownlist after inserting data into database for perticular emp..id.. thanks in advance.. please help me to solve this problem...
If you want to really hide id from dropdown then you can add field (may be bit datatype and name as addedRecord) in the table from where Id is coming. set that field if record is added and bind drop down with only ids that are not set. Otherwise you can check in database before adding personnel info, if that exists then don't insert it.
Use your postback correctly Give this in your pageload()
if(!postback)
{
ddlbindcode();//dropdownlist bind query
}

DataKeyNames for different tables with different primary key names

I'm wondering if there is a way to use datakeynames to access the primary keys of different tables if those primary key names are different in those tables.
For example, I have a table called Table1 and Table2 where the primary keys are Table1ID and Table2ID respectively.
My ultimate goal is to combine the contents of both tables into 1 gridview, and to generate a hyperlink for both every row. So my c# looks something like this:
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand command = new SqlCommand("(SELECT Table1ID, Title FROM Table1" +
"UNION ALL SELECT Table2ID, Title FROM Table2)", connection);
GridView1.DataBind();
}
Then in my Gridview_Databound method, I go through and set the hyperlinks for each row individually. The problem is how do I access Table1ID and Table2ID? In my .aspx code, can I set that to be a BoundField because the DataField won't be consistent? I can't just do the following because then it neglects Table2ID right?
<asp:BoundField DataField="Table1ID"/>
Maybe I need to use a templateField or something?
You can use templatefield as below code
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkEdit" ToolTip="Click to edit" CommandName="EditContent" CommandArgument='<%# Eval("Table1ID") %>' />
</ItemTemplate>
</asp:TemplateField>
Now on your OnRowCommand="GridView1_RowCommand" you will get the pk id of this tables.
In GridView control you can have a TemplateField containing Hyperlink (see the link to my article for details of this solution).
Also, it might be less labor-intensive if you use SqlDataSource assigning your select statement to its property and passing it to GridView.DataSource property. It will take just several lines of code and do the job for you. Regards, AB

Cascading dropDownLists in repeater. DropDownLists with SQL source and add/delete option

What is the trick to implement the following interface in ASP.NET?
I think the screenshot should explain everything.
Both dropDownLists work on SQL tables. [Categories],[Items] bound with ID_category PK/FK
Number of rows variable (by default 1 row with "Add" button)
Choosing category changes only the content of the dropDownList next to it and the content stays the same when other rows get added/deleted
"Add" button saves current setup and adds new row with either "Select value" or eventually 1st category/1st item selected
How to store previously selected categories/items and the dropDown filtering by category, while adding, changing, deleting items or some other PostBack on website?
What I have tried so far is to use Repeater with DataSet, however I have encountered several different problems:
Was unable to preserve the relations between previous dropDowns
DropDowns resetting one another
2nd dropDown losing filtering when adding new row
I can post some code but since it doesn't fully work, perhaps a totally different approach would be better. Basically I started with this tutorial. The repeater currently looks like:
<repeater>
<itemtemplate>
<dropDown DataSource="categoriesDS"
value='<%# DataBinder.Eval(Container.DataItem, "Category") %>'.../>
<dropDown DataSource="itemsDS"
value='<%# DataBinder.Eval(Container.DataItem, "Item") %>'.../>
<button CommandName='<%# DataBinder.Eval(Container.DataItem, "Button") %>'
Text='<%# DataBinder.Eval(Container.DataItem, "Button") %>' .../>
</itemtemplate>
</repeater>
Thanks in advance for any suggestions or solutions and I hope it'll be helpful for others.
Ajax Cascading DropDownlist
It is very simple to use.

Categories