How to add Link Button In dynamically in Autogenerated Gridview - c#

How to add Link Button In dynamically in Autogenerated Gridview and How write onclick event for that link button.
<asp:GridView ID="GridView4" runat="server" BorderColor="#3366CC" BorderStyle="None"
BorderWidth="1px" CellPadding="4" ShowHeaderWhenEmpty="True" Width="996px" HeaderStyle-Wrap="false"
ItemStyle-Wrap="false" OnRowDataBound="GridView4_RowDataBound">
<PagerSettings Mode="NextPreviousFirstLast" FirstPageText="First" LastPageText="Last"
NextPageText="Next" PreviousPageText="Previous" />
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" Height="10px" />
<RowStyle ForeColor="white" HorizontalAlign="Center" Font-Names="Microsoft Sans Serif" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
Binded Datas to this gridview dynamically..the Header and data's changes everytime.
Need to bind all the datas in link button and to write code for that button click.
Please help.........................

You don't need to add a link button.
You need to add
DataKeys, a comma separated list of fields from GridView4 Dataset
Enable row selection
Add a row selection handler
<asp:GridView ID="GridView4" runat="server"
AutoGenerateSelectButton="True"
OnSelectedIndexChanged="GridView4_SelectedIndexChanged"
DataKeyNames="XXX,YYY,ZZZ">
...
</asp:GridView
Alternatively, the above can all be done in the code behind.
Selecting a row will fire the event handler where you retrieve the data Keys
protected void GridView4_SelectedIndexChanged( object sender, EventArgs e )
{
// Retrieve data from selected row
String field1 = (String) GridView1.SelectedDataKey.Values[ "XXX" ];
int field2 = (int) GridView1.SelectedDataKey.Values[ "YYY" ];
double field3 = (double) GridView1.SelectedDataKey.Values[ "ZZZ" ];
PopulateYourOtherGridviewDataSource(field1, field2, field3);
GridViewOther.DataBind();
}

Related

Sorted Datatable value differs in UI gridview in c#

I have a datatable with sorted column values and when I bind them to the gridview I'm not able to see the same order in the gridview like I have in the datatable.
Sorting event is also disable in gridview.
Can anyone please provide suggestions.
HTML:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" ShowHeaderWhenEmpty="true" EmptyDataText="No Records Found" OnRowDataBound="GridView1_RowDataBound" AllowSorting="true" OnSorting="GridView1_Sorting"
OnPageIndexChanging="GridView1_PageIndexChanging" AllowPaging="true" CellPadding="1" PageSize="200" AutoPostBack="true" AllowCustomPaging="true" ShowHeader="true"
CellSpacing="1" BackColor="#e7e7e8" BorderColor="#e7e7e8" GridLines="Both" CssClass="GridViewStyleB" Font-Names="Calibri" Font-Size="10pt">
<PagerSettings Mode="NumericFirstLast" PageButtonCount="4" FirstPageText="First" LastPageText="Last" Position="Top" Visible="true" />
<PagerStyle BackColor="#e7e7e8" ForeColor="Black" HorizontalAlign="left" />
<HeaderStyle CssClass="RowStyle" ForeColor="Black" BackColor="#a9a9a9" Font-Underline="false" HorizontalAlign="Left" />
<RowStyle CssClass="RowStyle" HorizontalAlign="Left" BorderColor="#E7E7E8" ForeColor="Black" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" BorderColor="#E7E7E8" ForeColor="Black" BackColor="#e7e7e8" />
<EmptyDataRowStyle HorizontalAlign="Center" />
</asp:GridView>
Code:
DataTable dtColumns = FromDataTable();
GridView1.DataSource = dtColumns;
GridView1.DataBind();
dtColumns datatable have sorted data and I when I bind them to the gridview the order changes.
If you insert a breakpoint at GridView1.DataSource = dtColumns, and inspect the dtColumns object, can you confirm the sort order of the rows? What is the underlying query used to select the data? If it's from a single table, what data type is the primary key?
I think if you check those things, you will find your answer, but if not, you should update your post to include that stuff :)
EDIT
Here is something you can try to force the sort, after you perform the databinding:
GridView1.Sort("column name", System.Web.UI.WebControls.SortDirection.Descending);

Weird behavior when trying to update text in a GridView cell

I am trying to prepend some text to what's already in a GridView cell in the RowDataBound event:
protected void gvPatientSearch_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow dr = ((DataRowView)e.Row.DataItem).Row;
if (Convert.ToBoolean(dr["Confidential"]))
{
String name = String.Copy(e.Row.Cells[1].Text);
//the problem is the following line
e.Row.Cells[1].Text = "<b><font color='red'>!</font></b>" + name;
}
}
}
For some reason it seems that no matter what I do the original text is deleted. When I remove the line below the comment the name displays normally without the exclamation point; when I add the append code, for some reason the original text becomes a blank string and I only get the exclamation point. I have tried this with and without the String.Copy - I didn't think this would be needed but figured I would try it just in case. No luck.
I don't think this is relevant, but the first column in the row is a hidden column that contains a 1 or a 0. If the value is 1, I want to add the exclamation point. The data is there and this part is being called correctly, I just can't get the name to stay put.
Any ideas why this would be happening?
EDIT: Front end code below
<asp:GridView ID="gvPatientSearch" runat="server" Width="100%" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" AllowSorting="True"
PageSize="25" OnPageIndexChanging="gvPatientSearch_PageIndexChanging" OnSorting="gvPatientSearch_Sorting" OnRowDataBound="gvPatientSearch_RowDataBound"
AutoGenerateColumns="false" PagerSettings-Position="TopAndBottom" PagerStyle-HorizontalAlign="Right" PagerSettings-Mode="NumericFirstLast" PagerSettings-PageButtonCount="5"
PagerSettings-FirstPageText=" First " PagerSettings-LastPageText=" Last " PagerSettings-PreviousPageText=" Previous " PagerSettings-NextPageText=" Next ">
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
<Columns>
<asp:BoundField HeaderText="Confidential" DataField="Confidential" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol"></asp:BoundField>
<asp:HyperLinkField DataTextField="PatientName" DataNavigateUrlFields="PatientIdInternal" DataNavigateUrlFormatString="PatientProfile.aspx?InternalID={0}" HeaderText="Patient Name"
SortExpression="PatientName" />
<asp:BoundField DataField="PatientID" HeaderText="Patient ID" SortExpression="PatientID" />
<asp:BoundField DataField="AccountNumber" HeaderText="Account Number" SortExpression="AccountNumber" />
<asp:BoundField DataField="DateOfBirth" HeaderText="Date Of Birth" SortExpression="DateOfBirth" DataFormatString="{0:d}" />
<asp:BoundField DataField="PracticeName" HeaderText="Practice Name" SortExpression="PracticeName" />
<asp:BoundField DataField="PatientIdInternal" HeaderText="Internal ID" SortExpression="PatientIdInternal" Visible="false" />
</Columns>
</asp:GridView>
I can see the values of all the other fields showing up correctly in Visual Studio at this part of the code, only the name field that I am trying to modify shows as an empty string.
A HyperLinkField is rendered as a Hyperlink control, and for this reason you cannot retrieve the cell's text directly. If you want the text, you must retrieve it from the control, not the cell:
HyperLink myLink = e.Row.Cells[1].Controls[0] as HyperLink;
String name = myLink.text;
An alternative would be to grab the name directly from the datasource by doing DataBinder.Eval(e.Row.DataItem, "name") in your code-behind.
I don't know why that's happening, but I think you can work around it by applying you logic with a function like this:
public string Exclaim(bool confidential, string originalText)
{
if (confidential) {
return "<b><font color='red'>!</font></b>" + originalText;
} else {
return originalText;
}
}
In your gridview, invoke the function using:
<asp:TemplateField>
<ItemTemplate>
<%# Exclaim(Eval("Confidential"), Eval("Name"))%>
</ItemTemplate>
</asp:TemplateField>
I think that would work.
I went ahead and did it by changing the offending line to this:
e.Row.Cells[1].Text = "<b>font color='red'>!</font></b> " + Convert.ToString(dr["PatientName"]);
Still don't know why the other way doesn't work, if anyone else does and answers I will mark it correct.

Change value of cells before it's rendered into datagrid

I have a web app I'm trying to write that will get the percentages of supplies left in a printer. and display that in a friendly 1-100 percent number. to get that number i must multiply what is left by 100 then divide that by the total possible.
I have not been able to take the data that is coming from a sql server table and modify it before it is rendered into the data gridview. Any help would be appreciated.
I've already tried in the code behind to convert it to integer with no luck. Here is my code.
ASPX
<asp:GridView ID="GridView2" runat="server" AllowSorting="True"
AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84"
BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" OnRowDataBound = "changeToPercent"
DataSourceID="SqlDataSource1" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="p_ipaddress" HeaderText="p_ipaddress"
SortExpression="p_ipaddress" />
<asp:BoundField DataField="s_prtmarkerssuppliesdescription"
HeaderText="s_prtmarkerssuppliesdescription"
SortExpression="s_prtmarkerssuppliesdescription" />
<asp:BoundField DataField="s_prtMarkersSuppliesLevel"
HeaderText="s_prtMarkersSuppliesLevel"
SortExpression="s_prtMarkersSuppliesLevel" />
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:XrxDBCWWConnectionString %>"
SelectCommand="usp_SUPPLYPERCENTAGE" SelectCommandType="StoredProcedure"
CancelSelectOnNullParameter="False">
<SelectParameters>
<asp:ControlParameter ControlID="percentBox" DefaultValue="10"
Name="PCT_REQUESTED" PropertyName="Text" Type="Int32" />
<asp:Parameter DefaultValue="" Name="PRINTER_ID" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
I have no CS Code to use because everything i have tried has failed miserably
Try wiring up the GridView's RowDataBound event, where you would have access to the Row data, and can update them before it gets bound to the grid view.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx
void GridView2_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Display the company name in italics.
e.Row.Cells[1].Text = "<i>" + e.Row.Cells[1].Text + "</i>";
}
}
Sorry about the premature post. I had given up entirely editing my code so instead i went to the source and looked at the stored procedure to see if i could make it work there. Just so happens that you can do Mathmatical function INSIDE your SELECT statement.
This is what i added in the select.
SELECT ((s_prtMarkersSuppliesLevel *100) / s.s_prtMarkersSuppliesMaxCapacity) as s_prtMarkersSuppliesLevel

Disable text wrap in asp.net gridview

The output is like this:
MyNameIsJohnSmithAnd
Imaperson
What I want is to display it in only one line
MyNameIsJohnSmithAndImaperson
My Aspx gridview code is:
<asp:GridView ID="GridView1" runat="server" BackColor="LightGoldenrodYellow"
BorderColor="Tan" BorderWidth="1px" CellPadding="5" Font-Names="Calibri"
Font-Size="Medium" Font-Underline="False" ForeColor="Black">
<RowStyle Wrap="False"/>
<EmptyDataRowStyle Wrap="False"/>
<FooterStyle BackColor="Tan" BorderColor="Black" BorderStyle="Solid" Wrap="False"/>
<PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
HorizontalAlign="Center" Wrap="False" />
<SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" Wrap="False"/>
<HeaderStyle BackColor="Tan" BorderStyle="Solid" Font-Bold="True" Wrap="False"/>
<EditRowStyle Wrap="False"/>
<AlternatingRowStyle BackColor="PaleGoldenrod" Wrap="False"/>
</asp:GridView>
I disabled all the wrap property to false in gridview. but the text still wraps.
You have to set the gridview's individual column's word wrap to False as well.
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" >
<ItemStyle Wrap="False" />
</asp:BoundField>
Try adding this event to your gridview.
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < e.Row.Cells.Count; i++)
{
e.Row.Cells[i].Attributes.Add("style", "white-space: nowrap;");
}
}
Here is the reference.
Very simple in .Net Select your grid view (as in Design mode) in property window and follow this
RowStyle -->Font -->>Wrap=False
Thats done
You can do this by css.
#GridView1
{
white-space:nowrap;
}
My column header text was wrapping so I ended up needing a slightly different solution but similar to what user3578419 suggested.
In design view, I edited the 'ColumnHeadersDefaultCellStyle' property and changed the 'WrapMode' value to 'False'.

Delete Item From Dynamic Gridview

I have a dynamic gridview with data pulled from oracle database.
<asp:GridView ID="gvData" OnRowDataBound="gvData_RowDataBound" OnPreRender="gvData_PreRender" OnSelectedIndexChanged="gvData_SelectedIndexChanged" OnLoad="gvData_Load" OnRowCommand="gvData_RowCommand" runat="server" CellPadding="4" ForeColor="#333333" AllowPaging="True" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" DataSourceID="DS" AllowSorting="True" AutoGenerateSelectButton="True" PageSize="10" ShowFooter="True">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#CCCCCC" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
<asp:SqlDataSource ID="DS" runat="server">
</asp:SqlDataSource>
I am trying to write DELETE/UPDATE statements. I am having a problem with getting values from gridview and adding them to the parameters os SQL statements.
protected void gvData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DS.DeleteCommand =
"DELETE FROM TABLE " +
"WHERE PROBLEM_DEPTH_MD = :PROBLEM_DEPTH_MD";
"AND API = :API " +
"AND BUS_AREA_ID = :BUS_AREA_ID";
DS.DeleteParameters.Add(new Parameter("PROBLEM_DEPTH_MD", TypeCode.String, ??GridViewItemValue??));
}
I don't know how to get a value from the gridview. Any suggestions? Thanks!
First off you need to mention the DataKeyName to your gridview of your Primary key Column and then you can access the value of the Selected row of the Gridview like... e.Keys["DataKeyName"]
If you want to access a non key field, then it should be like... e.Values["FieldName"]
Mention DataKeyName like... <asp:GridView ID="gvData" DataKeyNames="PrimaryKeyColumn"
You will need to set the DataKeyNames for you GridView.
You can then use the GridViewDeleteEventArgs to get the Keys property. This will be a dictionary of Key/Value pairs which correspond to the DataKeyFields which you set. In essence it allows you to get your primary keys-- which is what you need to delete.
assuming primary keys are PROBLEM_DEPTH_MD, API, AND BUS_ARE_ID, you would set the DataKeyNames to be "PROBLEM_DEPTH_MD,API,AND BUS_ARE_ID".
You could then grab these keys in your delete event with e.Keys. If you loop over them you should be able to get the values to add your parameters.
Here is some more information on this:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.datakeynames.aspx

Categories