Specifying constant value in the gridview hyperlink - asp.net

I have a gridview with a HyperLinkField column where the DataNavigateUrlFormatString is as following:
DataNavigateUrlFormatString="DetailedPage.aspx?OrderNo={0}"
I would like to add to the above DataNavigateUrlFormatstring another value – constant - so that the called page (DetailedPage can get both the value of OrderNo (passed dynamically) and the same value for all rows.
For example, the url would be something like:
DetailedPage.aspx?OrderNo=100&filename=’myfilename.doc’
Note, again that the name ‘myfilename.doc’ is the same for all rows but will be known in the OnLoad of the page. Ideally I would like the second value (e.g. myfilename.doc) to be hidden from the URL
but if this is not possible, it will still work.
How can I do it?

Use a TemplateField with a HyperLink control inside and then in the RowDataBound event in code-behind, just set the NavigateUrl property to the value, like this:
Markup:
<asp:GridView id="GridView1" runat="server"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
...Other columns here...
<asp:TemplateField>
<ItemTempalte>
<asp:HyperLink id="HyperLink1" runat="server" Text="Details" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
// Only interact with the data rows, ignore header and footer rows
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Find the hyperlink control by ID
var theHyperLink = e.Row.FindControl("HyperLink1") as HyperLink;
// Verify we found the hyperlink before we try to use it
if(theHyperLink != null)
{
// Set the NavigateUrl value here
theHyperLink.NavigateUrl = String.Format("DetailedPage.aspx?OrderNo={0}&filename='{1}'", theOrderNumber.ToString(), theFileName);
}
}
}
Note: theOrderNumber and theFileName would be values determined upon load of the page from the database, for example.

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
}
}
}

ASP.Net, Datagrid: render column differently based upon value?

I've looked and looked and I'm not seeing the answer to this.
I have a datetime value that's getting bound to a datagrid. I want to display the column as either the datetime, or if said datetime is null, an asp:button for the users to click.
I can't seem to find specific information on how to do it. My initial approach was <% if blah blah then %>, but I can't seem to get at the dataitem in that manner. I've also looked at events, but nothing is jumping out at me as being the solution (I'm sure I'm wrong, I'm just not seeing it).
Any suggestions?
Assuming that you actually mean GridView instead of DataGrid, otherwise it would work similarly(ItemDataBound etc.).
You could use a TemplateField with a Label and a Button and switch visibility of both controls in RowDataBound:
protected void Grid_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var row = ((DataRowView)e.Row.DataItem).Row;
DateTime? date = row.Field<DateTime?>("DateColumn");
var lblDate = (Label)e.Row.FindControl("LblDate");
var btnDate = (Button)e.Row.FindControl("BtnDate");
lblDate.Visible = date.HasValue;
btnDate.Visible = !date.HasValue;
if (date.HasValue) lblDate.Text = date.ToString();
}
}
aspx:
<asp:GridView ID="GridView1" AutoGenerateColumns="false" OnRowDataBound="Grid_RowDataBound" runat="server">
<Columns>
<asp:TemplateField HeaderText="DateColumn">
<ItemTemplate>
<asp:Label ID="LblDate" runat="server"></asp:Label>
<asp:Button ID="BtnDate" Text="click me" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You should use Gridview if you are using ASP.NET 3.5 or higher. Using a templatefield column, add a button and label. In the rowdatabound event, you should show only the button or the label, using the Visible property, depending on whether there's a date or not.

writing code in button's click event in gridview

i have added a button control in gridview and i want to redirect
to the another page on button's click event,
and also i want to access the values of selected row in a gridview and show that values on other page on button
click event which is inside the gridview,, can anybody plz help me out in this .
this should be helpful: http://msdn.microsoft.com/en-us/library/bb907626.aspx
for accessing values inside RowCommand event find your row first (by index):
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = MyGridView.Rows[index];
and then controls inside it which holds the values you need:
Label MyLabel= (Label)row.FindControl(MyLabel);
after that all you need to do is to transfer to your page and send values from your controls with it (do that with querystring):
Server.Transfer("MyPage.aspx?value="+MyLabel.Text)
here you can read more about gridview RowCommand event: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx
You need to add either a ButtonField or a TemplateField with a button inside and then you can add your code to the RowCommand and use the e.CommandName and e.CommandArgument
To redirect you can use Response.Redirect(address)
To see the values it depends where in the program you want to do it. If during databinding you can use the dataitem("column"). Outside of databinding you can go through the Gridview.Rows collection for the row you want and then look at the row.Cells(columnNumber).Text to see the value.
we have an event in gridview called, gridview rowcommand event, in that you can write the code for redirecting to another page using button. First you have to bind the value of which you want to pass in button property called commandargument.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Response.Redirect("abc.aspx?id=" + e.CommandArgument);
//here id means passing the value using querystring to another page.
}
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" />
<asp:BoundField HeaderText="Name" DataField="fullname" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button runat="server" ID="btnDelete" Text="Delete" OnClick="btnDelete_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
// This focuses the current row where the button lies. you can perform all events of server-controlls
//instead of Button e.g LinkButton, Dropdownlist index changes...
protected void btnDelete_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
GridViewRow gvRow = (GridViewRow)btn.NamingContainer;
string id = gvRow.Cells[0].Text;
string name = gvRow.Cells[1].Text;
//use these values in query string or any logic you prefer for cross page posting
Response.Redirect("your URL ?id=" + id + "&name=" + name);
}

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

How do I find the Client ID of control within an ASP.NET GridView?

I have a asp:GridView which contains a asp:TextBox within a TemplateField. I would like to obtain it's ID for use in javascript. Something like this:
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="textDateSent" runat="server" />
<input type="button" value='Today'
onclick="setToday('<%# textDateSent.ClientID %>');" />
</ItemTemplate>
</asp:TemplateField>
But when I compile, I get an error:
The name 'textDateSent' does not exist in the current context
Anybody know how to get the client ID of this TextBox?
Try this:
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="textDateSent" runat="server">
</asp:TextBox>
<input type="button" value='Today' onclick="setToday('<%# ((GridViewRow)Container).FindControl("textDateSent").ClientID %>');" />
</ItemTemplate>
</asp:TemplateField>
Maybe you don't want to do it where you need the ClientID. Check out this post here where the controls in a row are referenced in a generic way.
Change <%# textDateSent.ClientID %> to <%= textDateSent.ClientID %>.
Argh, you may need to use the OnDataBinding event of the grid view. Then put a literal control in your javascript. Then you can get the clientID of the text box and feed that into your literal control.
protected void GridViewName_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Create an instance of the datarow
DataRowView rowData = (DataRowView)e.Row.DataItem;
//locate your text box
//locate your literal control
//insert the clientID of the textbox into the literal control
}
}
Look here for a great detailed tutorial on working within this context.
You can get client id like this:
protected void Gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string strClientID = ((TextBox)e.Row.FindControl("txtName")).ClientID;
}
}
This will give unique client ID for each textbox in all rows.
I just do this...
var tbl = document.getElementById('<%=GridView.ClientID%>');
var checkBox = tbl.rows[i].cells[11].getElementsByTagName("input")[0].id;
the cell should always be the same and it gets rendered into an input. You may have to change the number at the end if you have more then one input in that cell. This will give you the new clientid/id of the input object (checkbox or whatever)
This is what I did. In the aspx page I just passed the entire object to the javascript function, so I didn't even meed to client id. In my case the object was a drop down list in the EditItemTemplate of the GridView. I added an html onchange(this) event in the aspx code.
<asp:DropDownList ID="custReqRegionsDDL" runat="server" onchange='custReqRegionsDDLOnChange(this)'>
</asp:DropDownList>
here is my javascript
function custReqRegionsDDLOnChange(myDDL)
{
alert('selected text=' + myDDL.options[myDDL.selectedIndex].text);
}

Resources