asp.net binding query output into dropdown list in gridview - asp.net

this is for ticketing system where the tickets are in different status like 'open, rejected, closed, resolved..'
In asp.net i have a gridview and in the gridview there are textboxes and a dropdownlist.
i can get output from the database and get to populate it in the gridview and also the contents in the dropdown list are also displayed.
how can i get to bind the data of the dropdownlist in the grid to that of the output of the query. if the ticket is closed it should select closed, if the ticket is rejected it should select rejected.
in the onrowCommand, i fetch data from another table and populate into the dropdown list. this is the full list of status like 'oopen, rejected, closed, resolved..'

Your question is missing details like what markup you have used for gridview and also what code you have for RowDataBound event.
So, I have provided a sample answer that you can easily adapt to your situation.
I am assuming you have a gridview with an id of GridView1 that contains the following ItemTemplate ( other columns have been omitted since they are not needed to understand this approach).
You should have a hidden field in the template so you can store the current status of the row; also when you are binding your gridview you should be getting a column called Status for the row.
Sample Markup
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnRowDataBound="GridView1_OnRowDataBound">
<Columns>
<asp:TemplateField HeaderText = "Status">
<ItemTemplate>
<asp:HiddenField ID="hfStatus" runat="server" Value='<%# Eval("Status") %>' />
<asp:DropDownList ID="ddlStatus" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Then in your RowDataBound event where you are binding the dropdown for the row, you need to get the value of hidden field hfStatus and then set the selected item of dropdown using this value.
I have assumed that a method called GetStatusDropDownListData is there that gets the data for binding dropdown list.
Sample RowDataBound event
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList ddlStatus = (e.Row.FindControl("ddlStatus") as DropDownList);
ddlStatus.DataSource = GetStatusDropDownListData();
ddlStatus.DataTextField = "Status";
ddlStatus.DataValueField = "Status";
ddlStatus.DataBind();
//Select the Status in DropDownList
string currentStatus = (e.Row.FindControl("hfStatus") as HiddenField).Value;
ddlStatus.Items.FindByValue(currentStatus).Selected = true;
}
}

i had used this code and its working now:
in asp file:
' Visible = "false" />
in the .cs file
string currentStatus = (e.Row.FindControl("lblStatus") as Label).Text;
ddlStatus.Items.FindByValue(currentStatus).Selected = true;

Related

select data from gridview field and populate textbox

I'm trying to populate a single text box (or parameter) with data from a gridview column when I click on a button in that row.
Gridview gets it data from a sqlconnection
the gridview is
| Drawing |
| 12345 | VIEW
| 12346 | VIEW
the VIEW is a template button with an onclick event, when the user clicks the button the data from the Drawing column (12345) should be passed to ether a textbox or a paremeter. (this is the part I dont know how to do) once the Iv got the number in a textbox I can use it as pareameter and then a pdf is opened of that drawing, I have code for this and is working.
thanks for any help
If you are using C#, the simplest thing to do would be to add an in-built select command button to the gridview rows at runtime. Then on the selectedindexchanged event of the gridview simply access the cell of the selected row that you want the value from. You can then assign that string to anything you want. Like so:
protected void myGridView_SelectedIndexChanged(object sender, EventArgs e)
{
string myString = myGridView.SelectedRow.Cells[4].Text.ToString();
TextBox1.Text = myString;
}
Remember that the cell index collection is zero based, so [0] is actually the first cell in the row.
Use TemplateFields and the grid view's OnRowCommand event, like this:
Markup:
<asp:gridview id="GridView1"
OnRowCommand="GridView1_RowCommand"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="TextBoxDrawing" runat="server"
Text="<%# Eval("Drawing")) %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="selc" runat="server" Text="View"
CommandName="View"
CommandArgument="<%# ((GridViewRow)Container).RowIndex %> />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked
if(e.CommandName == "View")
{
// Convert the row index stored in the CommandArgument
// property to an integer
var index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection
var row = GridView1.Rows[index];
// Find the drawing value
var theDrawingTextBox = row.FindControl("TextBoxDrawing") as TextBox;
// Verify the text box exists before we try to use it
if(theDrawingTextBox != null)
{
var theDrawingValue = theDrawingTextBox.Text;
// Do something here with drawing value
}
}
}

Determine the datatable index of the row clicked in GridView

I have a GridView in ASP.NET page. The GridView is bound to a dataset/datatabe. One of the columns of the grid is a command button and the gridview has method OnRowCommand (e.g. OnRowCommand="GridView_RowCommand") specified.
When user clicks on the button in the grid, the method GridView_RowCommand fires. I would like to find the index to the DataTable for the row where button was clicked. Note, that I am not looking for index to the GridView row but rather the index to the DataTable bound to the GridView.
Thank you in advance for your help.
You have a few options and it depends on the amount of data you are binding to the gridview, one you could save the dataset/datatable to Session[""] as you bind or you could retrieve the data from the database again once you have the unique id of the row. You could create the following on your gridview:
<asp:GridView ID="gvCustomer" runat="server"
AutoGenerateColumns="False" DataKeyNames="yourId" onrowcommand="gvCustomer_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkAction" runat="server" Text="Do Something" CommandName="yourEvent" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
then in the code behind for the RowCommand event have:
protected void gvCustomer_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "yourEvent")
{
var row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
int rowId = Convert.ToInt32(gvCustomer.DataKeys[row.RowIndex]["yourId"]);
}
}
At this point you have the id which you could either query the database again or access the data source object that you save in to session before binding to the gridview
Or another alternative is:
<asp:LinkButton CommandArgument='<%#Eval("PrimaryKey")%>' />
Then you can get the arg with e.CommandArgument in the gvCustomer_RowCommand method

Getting an Instance of Dropdown list when clicking update on GridView in Asp.Net

I have a GridView with more than 30 columns. Most are plain controls but for some I have added a template control (DropDownList, Calendar and CheckBox control). Here is the aspx code for the control in question
<asp:TemplateField HeaderText="Field1 Caption" SortExpression="Field1">
<ItemTemplate>
<asp:Label ID="lblConstructionArea" runat="server" Text='<%# Eval("Field1") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlField1" EnableViewState="true" runat="server"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
I wanted a dropdown to be shown on the column when a user clicked on Edit. So I add this code (and the above EditItemTemplate)
protected void gvData_RowEditing(object sender, GridViewEditEventArgs e)
{
string fieldOne = CommonUtils.ExtractControlValue(e,"lblField1",gvData);
gvData.SelectedIndex = e.NewEditIndex;
gvData.EditIndex = e.NewEditIndex;
gvData.DataBind();
BindGridDropDownData(e, CommonUtils.GetConstructionAreas() ,"ddlConstructionArea", constructionArea, "Field1", fieldOne);
}
In the above code I am getting the current available and passing it to another method so that when the dropdown is displayed the selected index can be shown accurately. After this I do a change on the dropdownlist and click on the "Update button" on the GridView and the following event is triggered
protected void gvData_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int rowEditIndex = e.RowIndex;
GridViewRow gRow = gvData.Rows[rowEditIndex];
DropDownList ddlConstructionArea = (DropDownList) gvData.Rows[rowEditIndex].FindControl("ddlConstructionArea"); //This does not work
ddlConstructionArea = (DropDownList)gRow.FindControl("ddlConstructionArea");//This does not work
ddlConstructionArea = (DropDownList)gvData.Rows[rowEditIndex].Cells[7].FindControl("ddlConstructionArea");//this does not work either
gvData.EditIndex = -1;//this works and the text boxes disappear
gvData.DataBind();//this works and the old data shows up on the gridview
}
I am curious as to how to do an update on a Grid where I have the binding is runtime.
Actually in the markup, you have given ID of dropdownlist as ddlField1 and in codebehind, you are reffering it as ddlConstructionArea. Is this is what causing the update not to function?
The problem was with the way the grid was being bound. I had written code to refresh the grid on page load and anytime I clicked on the Edit button the page was being refreshed and the grid binding was getting triggered instead of the updating event. I removed the code refreshing the grid on page load and put it in the places where it is needed and the order of events were getting triggered the way I would want it to and the update worked perfectly without a problem.

find control in listview

By pressing button in GridView i need to find control in Listview.
<ItemTemplate>
<td>
<asp:Label ID="lblMarketLVBalanceHeader" runat="server" Text="Balance: "></asp:Label>
</td>
<td>
<asp:Label ID="lblMarketLVBalanceValue" runat="server" Text='<%# Bind("Money", "{0:####}$") %>'></asp:Label>
</td>
</ItemTemplate>
Code Behind:
protected void GVMarketItems_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Buy"))
{ GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
/* string itemID = row.Cells[0].Text;
string itemName = row.Cells[1].Text;
string itemCostStr = row.Cells[3].Text; */
string curBalanceStr = ((Label)LVMarketBalanceShow.FindControl("lblMarketLVBalanceValue")).Text;
}
Code seems find, but i have "Object reference not set to an instance of an object" when i'm trying to Find control.
string curBalanceStr = ((Label)LVMarketBalanceShow.FindControl("lblMarketLVBalanceValue")).Text;
Did the same to DetailsView and it was Ok.. What's wrong with ListView?
UPD: Trying to get first fow of listview
ListViewDataItem curBalanceLV = LVMarketBalanceShow.Items[0];
string curBalanceStr =((Label)curBalanceLV.FindControl("lblMarketLVBalanceValue")).Text;
But getting an error "Index was out of range."
I think you want to find the control within the specific row.
string curBalanceStr = ((Label)row.FindControl("lblMarketLVBalanceValue")).Text
Did the same to DetailsView and it was Ok.. What's wrong with
ListView?
A DetailsView is used to tackle with one row at a time so you can directly call FindControl() on the detailsview but gridview and listview are meant to display multiple records and your markup you define inside <ItemTemplate /> is just a template for each row. You'll be able to find the controls that you define in the template inside of each row.

how to access templatefield from code behind

the reason why i am looking to update dynamic is because i am using objectdatasource and my objectdatasource have a collection of object and within that object i have another object that i wanted to access so for an example:
+Student
......
......
......
-Courses
.........
.........
Name
Update end
how do i bind templatefield from code-behind?
<asp:Gridview ID="gridview1" runat="Server">
<columns>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:Gridview>
First of all define your key field in GridView control, just add net attribute to GridView markup: datakeynames="StudentID".
You can use both event handler for GridView: RowDataBound or RowCreated. Just add one of this event handler and find there control that is placed in your ItemTemplate. Like here, for instance:
void ProductsGridView_RowCreated(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Retrieve the LinkButton control from the first column.
Label someLabel = (Label)e.Row.FindControl("someLabel");
if (someLabel != null)
{
// Get Student index
int StudentId = (int)GridView.DataKeys[e.Row.RowIndex].Values[0];
// Set the Label Text
// Define here all the courses regarding to current student id
someLabel.Text = //
}
}
}
This example was gotten from MSDN
Here are some code samples from MSDN:
http://msdn.microsoft.com/en-us/library/aa479353.aspx
These are in VB but you should be able to locate C# also :-)
If you follow this link and scroll down you will find a code sample:
http://bytes.com/topic/asp-net/answers/624380-gridview-generated-programmatically

Resources