Change Dynamically the BoundFields in a GridView - c#

I have a GridView inside a UpdatePanel. In some cases, I have to show different columns in this GridView so I need to change the BoundFields that are specified in my aspx.
How can I change the BoundFields to make the GridView be filled for a different query and different fields ?
ASPX
<cc1:GridView ID="grdImoveis" CssClass="StyleGrid" Width="100%" runat="server" ShowHeader="false"
AutoGenerateColumns="False" DataSourceID="dsGrid" BorderWidth="0px" GridLines="None"
AllowPaging="True" EnableModelValidation="True" >
<AlternatingRowStyle BackColor="White" CssClass="EstiloDalinhaAlternativaGrid" HorizontalAlign="Center" />
<RowStyle CssClass="EstiloDalinhaGrid" HorizontalAlign="Center" />
<Columns>
<asp:BoundField HeaderText="Nome" DataField="NomeCompleto" />
<asp:BoundField HeaderText="Cargo" DataField="DescricaoCargo1" />
<asp:BoundField HeaderText="Data Cadastro" DataField="DataHora" />
<asp:TemplateField ControlStyle-CssClass="acoes_lista_imovel" HeaderText="Curso">
<ItemTemplate>
<div class="acoes_lista_imovel">
<%# montaIcones(Eval("Usuario_Id").ToString())%>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</cc1:GridView>
CODE BEHIND
protected void btnSelecionarData_OnClick(object sender, EventArgs e)
{
string select = string.Empty;
select += "SELECT San_Credenciada.Apelido, San_Usuario.NomeCompleto, San_Usuario.Usuario_Id, San_Usuario.DescricaoCargo1, "
+ "CONVERT(varchar, San_Usuario.DataHora, 103) AS DataHora, San_UsuarioCurso.Cv, San_UsuarioCurso.Institucional, "
+ "San_UsuarioCurso.Copon, San_UsuarioCurso.ManualCaptacaoESistema, San_UsuarioCurso.PosturaProfissional, San_UsuarioCurso.Certificado "
+ "FROM San_Usuario "
+ "JOIN San_Credenciada "
+ "ON San_Usuario.Credenciada_Id = San_Credenciada.Credenciada_Id "
+ "JOIN San_UsuarioCurso "
+ "ON San_Usuario.Usuario_Id = San_UsuarioCurso.Usuario_Id "
+ "WHERE San_Usuario.Provisorio = 1 "
+ "AND San_Usuario.Excluido = 0 "
+ "AND San_UsuarioCurso.DataCurso = '" + this.DtBusca.Value.ToString() +"' "
+ "GROUP BY San_Credenciada.Apelido, San_Usuario.NomeCompleto, San_Usuario.Usuario_Id, "
+ "San_Usuario.DescricaoCargo1, San_Usuario.DataHora, San_UsuarioCurso.Cv, San_UsuarioCurso.Institucional, "
+ "San_UsuarioCurso.Copon, San_UsuarioCurso.ManualCaptacaoESistema, San_UsuarioCurso.PosturaProfissional, San_UsuarioCurso.Certificado "
+ "ORDER BY San_Usuario.DataHora ASC ";
dsGrid.ConnectionString = c.Con;
dsGrid.SelectCommand = select;
dsGrid.Dispose();

If I understand your query correctly, you want to change columns. A simple solution for this is that do not specify fields in your aspx page, just set AutoGenrateColumns = True in your grid view decleratoin
Your grid should look like
<asp:GridView ID="gv" runat="server" AutoGenrateColumns="True" />
// Now in your code behind just specify its DataSource property it will fill up with your desired columns.
// Your query should contain only those columns which you want to show

you can put GridView and Enable "AutoGenerateColumns=True" and for each case that you like fill grid view.

you can use this code for create ImageField Programmatically :
ImageField img = new ImageField();
img.HeaderText = "Pictuer";
img.DataImageUrlField ="Pic";
img.DataImageUrlFormatString = "images\\{0}";
GridView1.AutoGenerateColumns = false;
GridView1.Columns.Add(img);

Related

delete row from gridview sql

I want to be able to delete a row when I click on the delete button on that gridview. I have the aspx page and the code behind as well as the app code. The DeletePaymentCondition runs the store procedure to delete the row. But somehow the overall code doesnt work
aspx
<asp:GridView ID="gridview1" runat="server" HorizontalAlign="left" AutoGenerateColumns="false" CssClass="table table-bordered " GridLines="None"
AllowSorting="True" OnRowDeleting="OnRowDeleting">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="left" HeaderText="Payment Condition" HeaderStyle-CssClass="OGColor" HeaderStyle-ForeColor="white" SortExpression="monthToQuarters">
<ItemTemplate>
<span style="font-size:12px; color: #2980b9; text-align:left">
<asp:Label ID="lblUserId" runat="server" Visible="true" Text="<%# bind('payConditionId')%>"/>
</span>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150"/>
</Columns>
</asp:GridView>
cs
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
Label lblEmpID = (Label)gridPayment.Rows[e.RowIndex].FindControl("lblUserId"); //This is Table Id load on Label1
int id = Convert.ToInt32(lblEmpID.Text.ToString());
dsPayment = objcommission.Delete(id);
gridPayment.DataSource = dsPayment.Tables[0];
gridPayment.DataBind();
}
app code
public DataSet DeletePayment(int id)
{
DataSet dsGetAllPayment;
dsGetAllPaymentCondition = SqlHelper.ExecuteDataset(OGconnection, CommandType.Text, "Delete FROM tblPay where pay ='" + id + "'");
return dsGetAllPayment;
}
You shoul execute two different SQL, one for the delete and a new select one to retreive the new data.
The DELETE should be executed using in a NonQuery because it does not return rows (only the number of rows affected).
public DataSet DeletePaymentCondition(int ids)
{
int rowsAffected = SqlHelper.ExecuteNonQuery(OGconnection, CommandType.Text, "Delete FROM [Accounting].[dbo].[tblPayConditions] where payConditionId ='" + ids + "'");
DataSet dsGetAllPaymentCondition = SqlHelper.ExecuteDataSet(OGconnection, CommandType.Text, "Select * FROM [Accounting].[dbo].[tblPayConditions]");
return dsGetAllPaymentCondition;
}
As a good praxys, you should consider changing it into parametrized queries. In this case it is safe because of the integer conversion, but in similar code with string parameters you would be prone to SQL Injection attacks
I got the solution. I've made changes to the cs file and as well as the code provided by bradbury9.
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = Convert.ToInt32(gridPaymentCondition.DataKeys[e.RowIndex].Value.ToString());
dsPaymentCondition = objcommission.DeletePaymentCondition(index);
gridPaymentCondition.DataSource = dsPaymentCondition.Tables[0];
updatePaymentConditionsWithoutRefresh();
}

Format Numbers to Money in ASP.NET Gridview using SQL Stored Procedure as Source

I am using a SQL Server stored procedure as source of my gridview when it loads. The query has column that results to numbers (money), I want the numerical outputs to have comma when it loads in gridview. Originally in SQL, The query result has no any formatting, as I have tried to practice putting the formatting in the front-end.
Before, I am able to achieve that by putting a boundfield in the gridview definition, and then put attribute name datafield, giving its value based on the name of the column or alias in SQL. However in my case this time, the stored procedure column has a dynamic alias, because it is resulting a column with a specific date (it is changing depending on the days of the week).
Stored procedure goes something like this (Last part)
set #query = 'select locationd, Name ' +
',(SUM(Day1)) as '+ '[' + #sdateVC1 + ']' +
',(SUM(Day2)) as '+ '[' + #sdateVC2 + ']' +
',(SUM(Day3)) as '+ '[' + #sdateVC3 + ']' +
',(SUM(Day4)) as '+ '[' + #sdateVC4 + ']' +
',(SUM(Day5)) as '+ '[' + #sdateVC5 + ']' +
',(SUM(Day6)) as '+ '[' + #sdateVC6 + ']' +
',(SUM(Day7)) as '+ '[' + #sdateVC7 + ']' +
',(SUM(ISNULL(Day1,0)) + SUM(ISNULL(Day2,0)) + SUM(ISNULL(Day3,0)) + SUM(ISNULL(Day4,0)) + SUM(ISNULL(Day5,0)) + SUM(ISNULL(Day6,0)) + SUM(ISNULL(Day7,0)))as ''TOTAL'' ' +
',RANK() over (partition by locationd order by ((SUM(ISNULL(Day1,0)) + SUM(ISNULL(Day2,0)) + SUM(ISNULL(Day3,0)) + SUM(ISNULL(Day4,0)) + SUM(ISNULL(Day5,0)) + SUM(ISNULL(Day6,0)) + SUM(ISNULL(Day7,0)))) DESC) as ''Ranking'' ' +
'from #newestWSR4 ' +
'group by locationd, Name ' +
--'order by locationd, Name '
'union all' +
' select ''-'', ''TOTAL'', sum(day1), sum(day2), sum(day3), sum(day4), sum(day5), sum(day6), sum(day7), (SUM(ISNULL(Day1,0)) + SUM(ISNULL(Day2,0)) + SUM(ISNULL(Day3,0)) + SUM(ISNULL(Day4,0)) + SUM(ISNULL(Day5,0)) + SUM(ISNULL(Day6,0)) + SUM(ISNULL(Day7,0))), ''-'' ' +
'from #newestWSR4 '
The gridview code in ASP.net is like this
<asp:GridView ID="grdWSR" runat="server" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black"
GridLines="Vertical" Font-Size="Smaller" EmptyDataText="No Records Found"
ShowHeaderWhenEmpty="True" width="100%" AutoGenerateColumns="false" >
<emptydatarowstyle backcolor="white" forecolor="black"/>
<emptydatatemplate> No Data Found.</emptydatatemplate>
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="locationd" />
<asp:BoundField DataField="name" />
<asp:BoundField Datafield="" DataFormatString="{0:#,##0.00;(#,##0.00);0}" />
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" Height="25px"/>
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
Please take note of this part in the code above
<asp:BoundField DataField="locationd" />
<asp:BoundField DataField="name" />
<asp:BoundField Datafield="" DataFormatString="{0:#,##0.00;(#,##0.00);0}" />
As you can see, I've put only three boundfield for testing purposes. In there I don't know what to put in the datafield value since , the alias column in SQL stored procedure is dynamically changing or not fixed, unlike with the first two boundfields (which column names / alias in SQL are fixed)
Is this case possible to be answered? or should I consider now doing the solution on back-end (SQL) to achieve my desired result?
Any help will be greatly appreciated!
i suggest you don't do any formatting thing in sp,
it will overload your system in terms of optimization,
prefer c# instead
DataTable dt=mySP();
for(i=0;i<dt.Rows.Count;i++)
{
dt.Rows[i][10]=Convert.ToDouble(dt.Rows[i][10]).ToString("#,###,###,###,###,##0.00");
}
GridView1.DatSource=dt;
try formatting the string like this in your stored procedure:
CONVERT(varchar, CAST(SUM(Day1) AS money), 1)
or like this -
FORMAT(SUM(Day1),'###,###,###')

Getting textbox.text in gridview auto generated edit control

Hi i am having a problem using the auto generated edit button in my gridview.
i am trying to get the username from the edit text box and insert it to my database like so:
<asp:TemplateField HeaderText="User Name">
<ItemTemplate>
<asp:Label ID="UserNamelbl" runat="server" Text='<%# Eval("Username") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="UserNameEdit" Width="100" Text='<%# Eval("Username") %>' Enabled="true" runat="server"></asp:TextBox></EditItemTemplate>
</asp:TemplateField>
c# method that occurs on the update click.
protected void UsersGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = UsersGridview.Rows[e.RowIndex];
Connect c = new Connect("EdenSiteDB.accdb");
string updatesql = "UPDATE Users Set Username= '" + ((TextBox)row.FindControl("UserNameEdit")).Text + "' , Email= '" + ((TextBox)row.FindControl("EmailEdit")).Text + "' , Admin= " + (((CheckBox)row.FindControl("IsAdminBoxEdit")).Checked).ToString() + " WHERE UserID= " + Session["UserId"].ToString() + ";";
OleDbCommand updatecmm = new OleDbCommand(updatesql);
c.TakeAction(updatecmm);
string usersql = "SELECT * FROM Users;";
dt = c.MakeConnection(usersql, "Users");
UsersGridview.EditIndex = -1;
DataBind();
}
While running this is the updatesql:
updatesql = "UPDATE Users Set Username= 'edmx0' , Email= 'edmx0.et#gmail.com' , Admin= True WHERE UserID= 17;"
these are the previouse values. not the new ones i just entered.
but when i debug it, my sql keeps coming up with the initial username, and not the one i just entered.
I assume it has something to do with my gridview binding at that moment but i don't know how to fix it.
Any help would be appreciated!
can you step through to a breakpoint at the OleDbCommand and post the result of
updatesql
before the update command runs?

how to use space inside string

i want use space inside string, i use this code:
var lst = Article.Select(a => new {a.ID, Name = " " + a.Name}).ToList();
gv.DataSource = lst.ToList();
gv.DataBind();
but its not working, with this code display name = " "Name.
and use this code:
var lst = Article.Select(a => new {a.ID, Name = " " + a.Name}).ToList();
gv.DataSource = lst.ToList();
gv.DataBind();
and with this code display name = " "Name.
please help me
Edit:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
<Columns>
...
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" ItemStyle-Width="300px" ItemStyle-HorizontalAlign="Right"></asp:BoundField>
...
</asp:GridView>
Edit2:
Answer:
Link1
Link2
Thank you to all.
will this work?
string constructor that constructs a string from a character a repeat count:
var lst = Article.Select(a => new {a.ID, Name = new string(' ', 8) + a.Name})
.ToList();
UPDATE 1
set property, HtmlEncode=False
<asp:BoundField DataField="Name" HtmlEncode="False" />
and enclosed the value with <pre> tag
var lst = Article.Select(a => new {a.ID, Name = "<pre> </pre>" + a.Name})
.ToList();
I am assuming the gv is an asp.net gridview control and that all your whitespace is being merged when displayed in a browser.
So, try something like this
<asp:BoundField DataField="Name">
<ItemStyle CssClass="NameCol" />
</asp:BoundField>
and in your css
..NameCol
{
padding-left:50px;
}
Try this sample way
a.Name.ToString().PadLeft(10," ")
Must use ToString()
Edit Try this
a.Name.PadLeft(10,' ')

Changing values inside my GridView on load with ASP.NET

I have a GridView that gets populated with data from a SQL database, very easy.
Now i want to replace values in my one column like so......
If c04_oprogrs value is a 1 then display Take in the GridView.
If c04_oprogrs value is 2 then display Available in the GridView.
What code changes must i make to change to my code to display the new values.
My Grid
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="281px" Width="940px"
Font-Size="X-Small" AllowPaging="True"
onpageindexchanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="c04_oprogrs" HeaderText="Order Progress"
SortExpression="c04_oprogrs" />
<asp:BoundField DataField="c04_orderno" HeaderText="Order No."
SortExpression="c04_orderno" />
<asp:BoundField DataField="c04_orddate" HeaderText="Date of Order"
SortExpression="c04_orddate" DataFormatString="{0:d/MM/yyyy}" />
<asp:BoundField DataField="c04_ordval" HeaderText="Order Value"
SortExpression="c04_ordval" DataFormatString="{0:R#,###,###.00}" />
<asp:BoundField DataField="c04_delval" HeaderText="Delivered Value"
SortExpression="c04_delval" DataFormatString="{0:R#,###,###.00}" />
<asp:BoundField DataField="c04_invval" HeaderText="Invoice Value"
SortExpression="c04_invval" DataFormatString="{0:R#,###,###.00}" />
<asp:BoundField DataField="c04_orddesc" HeaderText="Order Description"
SortExpression="c04_orddesc" >
<ControlStyle Width="300px" />
</asp:BoundField>
</Columns>
</asp:GridView>
My Page load
SqlConnection myConnection;
DataSet dataSet = new DataSet();
SqlDataAdapter adapter;
//making my connection
myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SAMRASConnectionString"].ConnectionString);
adapter = new SqlDataAdapter("Select TOP 40 c04_credno, c04_orderno, c04_orddate, c04_ordval, c04_delval, c04_invval, c04_oprogrs, c04_orddesc FROM C04ORDS WHERE c04_credno = '" + Session["CreditorNumber"] + "'AND c04_oprogrs <> 9 ORDER BY c04_orddate DESC", myConnection);
adapter.Fill(dataSet, "MyData");
GridView1.DataSource = dataSet;
Session["DataSource"] = dataSet;
GridView1.DataBind();
Etienne
EDIT:
MY FINAL SOLUTION
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Find the value in the c04_oprogrs column. You'll have to use
string value = e.Row.Cells[0].Text;
if (value == "1")
{
e.Row.Cells[0].Text = "Take";
}
else if (value == "2")
{
e.Row.Cells[0].Text = "Available";
}
}
}
You can use the RowDataBound event for this. Using this event you can alter the content of specific columns before the grid is rendered.
To clarify a little. First you add a template column with a label to your grid view (see also the answer by ranomore):
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="myLabel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Next you implement the RowDataBound event (I haven't checked the code below, so it may contain some syntax errors):
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Find the value in the c04_oprogrs column. You'll have to use
// some trial and error here to find the right control. The line
// below may provide the desired value but I'm not entirely sure.
string value = e.Row.Cells[0].Text;
// Next find the label in the template field.
Label myLabel = (Label) e.Row.FindControl("myLabel");
if (value == "1")
{
myLabel.Text = "Take";
}
else if (value == "2")
{
myLabel.Text = "Available";
}
}
}
You could use a template column and call a function in your code behind.
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" Text='<%#FieldDisplay(Eval("c04_oprogrs")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
then in your code behind do
protected string FieldDisplay(int c04_oprogrs)
{
string rtn = "DefaultValue";
if (c04_oprogrs == 1)
{
rtn = "Take";
}
else if (c04_oprogrs == 2)
{
rtn = "Available";
}
return rtn;
}
Without using a function. The ternary statement is in VB. If you have to nest another ternary statement to really test for 2 then it'd be easier to go with rwwilden's solution.
<asp:TemplateField HeaderText="Order Progress" SortExpression="c04_oprogrs" >
<ItemTemplate>
<asp:Label runat="server" ID="Label1" Text='<%# IIF(CInt(Eval("c04_oprogrs")) = 1, "Take", "Available") %>' />
</ItemTemplate>
</asp:TemplateField>
You could add a field in the SQL Statement
adapter = new SqlDataAdapter("Select TOP 40 c04_credno, c04_orderno, c04_orddate,
c04_ordval, c04_delval, c04_invval, c04_oprogrs, c04_orddesc ,
CASE c04_oprogrs WHEN 1 THEN "Take" WHEN 2 THEN "Available" ELSE "DontKnow" END AS
Status FROM C04ORDS WHERE c04_credno = '" + Session["CreditorNumber"] + "'AND
c04_oprogrs 9 ORDER BY c04_orddate DESC", myConnection);
And make that new field part of the BoundColumn in the markup.
Pardon my SQL syntax but I hope you get the idea.
EDIT: Do not use the syntax = '" + Session["CreditorNumber"] + "'.
See sql injection attack and how to avoid it using parameterized SQL.
This is the best efficient way.
Make a case in sql server view, like :-
select case <columnname>
when 1 then 'available'
when 0 then 'not available'
end as <columnname>
from <tablename>

Categories