I'd like to send gridview rows to an email on button press. The number of rows selected vary and use check boxes.
Background:
The app consists of 2 GridViews. One acts as a schedule, the other acts as a holding area for items taken out of the schedule. Included below is what I use to move Items out of the schedule. The code to put items back into schedule is identical, so it was not included.
The email function is to notify the user what specific items were taken out/put into schedule.
GridView1
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" AllowPaging="True" ShowHeaderWhenEmpty="True" BackColor="White" BorderColor="#003399" BorderStyle="None" BorderWidth="1px" CellPadding="4" OnPageIndexChanging="GridView1_PageIndexChanging" Width="450px">
<Columns>
<asp:BoundField DataField="VEH_SER_NO" SortExpression="VEH_SER_NO" ReadOnly="True">
<ItemStyle HorizontalAlign="Center" Width="75px" Wrap="False" />
</asp:BoundField>
<asp:BoundField DataField="DATE_BLD_RATE" SortExpression="DATE_BLD_RATE" ReadOnly="True" DataFormatString="{0:yyyy/MM/dd}">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="SEQ" SortExpression="SEQ" ReadOnly="True">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="SV_TYPE_CD" SortExpression="SV_TYPE_CD" ReadOnly="True" Visible="False" />
<asp:BoundField DataField="COMMENT" SortExpression="COMMENT" Visible="False" ReadOnly="False" />
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkSel" runat="server" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#99CCCC" ForeColor="White" HorizontalAlign="center" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
Code:
protected void cmdMoveRight_Click(object sender, EventArgs e)
{
if (drpReason0.SelectedValue != "" && drpReason.SelectedValue != "")
{
string strSQL = "SELECT VEH_SER_NO, DATE_BLD_RATE, SEQ, SV_TYPE_CD, COMMENT FROM Schedule " +
"WHERE Schedule.id = #ID";
MoveRows(GridView1, strSQL);
}
}
void MoveRows(GridView gv, string strSQL)
{
foreach (GridViewRow OneRow in gv.Rows)
{
CheckBox ckBox = OneRow.FindControl("cHkSel") as CheckBox;
if (ckBox.Checked)
{
int PKID = (int)gv.DataKeys[OneRow.RowIndex]["ID"];
SqlCommand cmdSQL = new SqlCommand(strSQL);
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
SqlRun(cmdSQL);
}
}
LoadGrids();
}
public void SqlRun(SqlCommand cmdSQL)
{
using (SqlConnection conn = new SqlConnection(cs))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
cmdSQL.ExecuteNonQuery();
}
}
}
Related
I am creating a gridview from SQL server in C#. Stored procedures are working just great. But now that I created the gridview and compiling. It is not even showing!
I've made quite a few times this, but now, I am unable to find out why it is not even showing.
This is my front.
<table cellpadding="2" cellspacing="0" border="0" width="100%" runat="server" id="tblVacantes">
<tr>
<td>
<asp:GridView ID="gvApplicants" runat="server" AllowPaging="True" AllowSorting="true"
AutoGenerateColumns="False" DataKeyNames="Id" CellPadding="5" ForeColor="#333333"
GridLines="None" PageSize="25" ShowFooter="True" Width="100%" Font-Size="9pt"
OnSorting="gvApplicants_Sorting" OnPageIndexChanging="gvApplicants_PageIndexChanging"
OnRowDataBound="gvApplicants_RowDataBound" EnablePersistedSelection="true">
<Columns>
<asp:BoundField HeaderText="Id" ReadOnly="True"
SortExpression="Id" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Top" />
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True"
SortExpression="Name" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Top" />
<asp:TemplateField HeaderText="Options" SortExpression="">
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<%# GetOpciones(Eval("username").ToString())%>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" ItemStyle-VerticalAlign="Top" />
</Columns>
<AlternatingRowStyle BackColor="Beige" Height="32px"/>
<RowStyle BackColor="White" Height="32px" />
<FooterStyle BackColor="#780C28" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#780C28" Font-Bold="False" ForeColor="White" HorizontalAlign="Left" />
<PagerSettings Mode="NumericFirstLast" PageButtonCount="20" Position="Bottom" />
<PagerStyle CssClass="pagination" VerticalAlign="Middle" HorizontalAlign="Center" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
</td>
</tr>
</table>
This is where I create all of my logic, where I store my SQL results in a list, where I plan to display them in the Grid. I have all getters and setters for ID, Nombre, Username and such.
public void LoadData()
{
gvApplicants.DataSource = GetApplicants();
gvApplicants.DataBind();
}
private List<ASF.Raffle.Entity.Staff> GetApplicants()
{
ASF.Raffle.BO.Staff dbCandidatos = new ASF.Raffle.BO.Staff();
List<ASF.Raffle.Entity.Staff> candidatos;
List<ASF.Raffle.Entity.Staff> candidatosFiltered = new List<ASF.Raffle.Entity.Staff>();
//primero filtro activos e inactivos.
return candidatos = dbCandidatos.GetAll();
}
protected string GetOpciones(string username)
{
ASF.Raffle.BO.Staff usr = new ASF.Raffle.BO.Staff();
ASF.Raffle.Entity.Staff u = usr.GetByUsername(username);
return usr.getAllOptions(u.Username);
}
public List<Entity.Staff> GetAll()
{
List<Entity.Staff> empleados = new List<Entity.Staff>();
//SQL Command para llamar el stored procedure
SqlCommand comando = new SqlCommand("dbo.[Empleados_GetAll]", base.Db);
//Ejecuta consulta
DataTable dtItem = base.Execute(comando);
//Transforma el Datatable en una lista de ResponsableFinancieros.
foreach (DataRow dr in dtItem.Rows)
empleados.Add(GetFromDataRow(dr));
return empleados;
}
But it is not even showing the table or throwing a connection error or anything related.
Thanks.
Thing is, I was missing a LoadData() method in the page_load. Therefore, it is now showing eveything correct now.
I have a reservation system and I am having a problem with my delete link that is inside my gridview that is supposedly to delete temporarily reserved rooms, it returns an error page stating that "Deleting is not supported by data source 'SqlDataSource1' unless DeleteCommand is specified." but when I relog-in the account I used the data was removed. Here is my code
ASP.net
<asp:GridView ID="cartGView" runat="server" DataKeyNames="ROOM_ID" AutoGenerateColumns="False" BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4" Width="100%" DataSourceID="SqlDataSource1" GridLines="Horizontal" OnRowDeleting="cartGView_RowDeleting">
<RowStyle HorizontalAlign ="Center" />
<Columns>
<asp:CommandField SelectText="Delete" ShowDeleteButton="True" />
<asp:BoundField DataField="ROOM_ID" HeaderText="Room ID" SortExpression="ROOM_ID" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
<asp:BoundField DataField="ROOM_TYPE" HeaderText="Room Type" SortExpression="ROOM_TYPE" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
<asp:BoundField DataField="NO_GUEST" HeaderText="Guest" SortExpression="NO_GUEST" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
<asp:BoundField DataField="PRICE" HeaderText="Price" SortExpression="PRICE" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
<asp:BoundField DataField="SUB_PRICE" HeaderText="Sub Price" SortExpression="SUB_PRICE" HeaderStyle-HorizontalAlign="Center">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
</asp:BoundField>
</Columns>
<EmptyDataTemplate>
<br></br><center>Select Room</center>
<br></br>
</EmptyDataTemplate>
<FooterStyle BackColor="White" ForeColor="#333333" />
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#487575" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#275353" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Bakasyunan %>" SelectCommand="SELECT DISTINCT [ROOM_ID], [ROOM_TYPE], [PRICE], [SUB_PRICE], [NO_GUEST] FROM [TBL_MyCart] WHERE ([USERNAME] = #USERNAME)" OnSelecting="SqlDataSource1_Selecting">
<SelectParameters>
<asp:SessionParameter Name="USERNAME" SessionField="username" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
C#:
protected void cartGView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
string roomid = Convert.ToString(cartGView.DataKeys[e.RowIndex].Values[0]);
cd.DeleteRecordWalkCart(roomid);
cartGView.DataSourceID = "SqlDataSource1";
cartGView.DataBind();
if (cartGView.Rows.Count == 0)
{
subtotalBox.Text = "P 0.00";
continueBtn.Enabled = false;
continueBtn.BackColor = System.Drawing.ColorTranslator.FromHtml("#2C2A2A");
}
else if (cartGView.Rows.Count > 0)
{
SqlCommand sumcmd = new SqlCommand("SELECT SUM(SUB_PRICE) FROM TBL_MyCart", conn); //<-- Add Subtotal
conn.Open();
string sum = sumcmd.ExecuteScalar().ToString();
conn.Close();
subtotalBox.Text = "P " + sum + ".00";
continueBtn.Enabled = true;
continueBtn.BackColor = System.Drawing.ColorTranslator.FromHtml("#6c0404");
}
}
catch(Exception ex)
{
Label1.Text = ex.Message;
}
}
Any help will be much appreciated! Thank you!
I'm new to ASP MVC. I want to load data from a database in DropDownList into a gridview. But DATA cannot load.
HTML CODE
<asp:BoundField DataField="id" HeaderText="Code">
<HeaderStyle Width="106px" HorizontalAlign="center" BorderColor="White" BorderWidth="1" />
<ItemStyle Width="102px" HorizontalAlign="center" BorderWidth="1px" />
</asp:BoundField>
<asp:BoundField DataField="name" HeaderText="Nom Cours">
<HeaderStyle Width="300px" HorizontalAlign="left" BorderColor="White" BorderWidth="1" />
<ItemStyle Width="300px" HorizontalAlign="left" BorderWidth="1px" />
</asp:BoundField>
<asp:templatefield HeaderText="Prix / Heure (HTG)">
<HeaderStyle Width="160px" HorizontalAlign="center" BorderColor="White" BorderWidth="1" />
<ItemStyle Width="160px" HorizontalAlign="center" BorderWidth="1px" />
<itemtemplate>
<asp:DropDownList ID="ddlprice" Width="160px" HorizontalAlign="center" runat="server">
</asp:DropDownList>
</itemtemplate>
</asp:templatefield>
<asp:templatefield HeaderText="Sélectionner">
<HeaderStyle Width="300px" HorizontalAlign="center" BorderColor="White" BorderWidth="1" />
<ItemStyle Width="300px" HorizontalAlign="center" BorderWidth="1px" />
<itemtemplate>
<asp:checkbox ID="cbSelect" CssClass="gridCB" runat="server" HorizontalAlign="center"></asp:checkbox>
</itemtemplate>
</asp:templatefield>
</Columns>
<FooterStyle BackColor="Tan" Height="30px" HorizontalAlign="Center" />
<HeaderStyle BackColor="Navy" Font-Bold="True" Height="22px" HorizontalAlign="Left"
ForeColor="WhiteSmoke" BorderColor="Navy" VerticalAlign="Top" BorderWidth="2px" Width="910px" Font-Size="Small" />
<PagerSettings Mode="NumericFirstLast" />
<PagerStyle BackColor="SkyBlue" ForeColor="WhiteSmoke"
HorizontalAlign="Center" />
<RowStyle Height="5px" Font-Size="Smaller" />
<SelectedRowStyle BackColor="Aquamarine" ForeColor="GhostWhite" BorderColor="Silver"
BorderStyle="None" />
<SortedAscendingCellStyle BackColor="SkyBlue" />
<SortedAscendingHeaderStyle BackColor="#DAC09E" />
<SortedDescendingCellStyle BackColor="#E1DB9C" />
<SortedDescendingHeaderStyle BackColor="#C2A47B" />
</asp:GridView>
</div>
C# CODE
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ddlClassroom.SelectedValue = "-1";
BindDataGridClass();
BindDataGridCourse();
loadListPrice();
}
private void loadListPrice()
{
List<Course> listPrice = Course.getListCoursePriceOrdered();
ddlprice.DataValueField = "id";
ddlprice.DataTextField = "price";
ddlprice.DataSource = listPrice;
ddlprice.DataBind();
//ddlprice.Items.Insert(0, new DropDownListItem("--Selectionner--", "-1"));
ddlprice.SelectedValue = "0";
}
First add the OnRowDataBound event to the GridView
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
Then in code behind
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//find the dropdownlist in the row with findcontrol and cast it back to one
DropDownList ddlprice = e.Row.FindControl("ddlprice") as DropDownList;
//you now have access to all the dropdownlist properties
ddlprice.DataSource = Course.getListCoursePriceOrdered();
ddlprice.DataValueField = "id";
ddlprice.DataTextField = "price";
ddlprice.DataBind();
ddlprice.SelectedValue = "0";
}
}
I am trying to get the selected row data and transfer it to a label on the same page. However I cannot get the Gridview.SelectedRow to work with my CommandName. I have tried everything....
I get the error. Object reference not set to an instance of an object. on Label2.Text
Here is my Code:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple ButtonField column fields are used, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Grab")
{
Label2.Text = GridView1.SelectedRow.Cells[2].Text;
Label3.Text = GridView1.SelectedRow.Cells[3].Text;
Label4.Text = GridView1.SelectedRow.Cells[4].Text;
Label5.Text = GridView1.SelectedRow.Cells[5].Text;
}
}
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataKeyNames="ID" DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical" CssClass="td" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Width="574px" onrowcommand="GridView1_RowCommand">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/images/edit.png" OnClick="ImageButton2_Click" />
<asp:ImageButton ID="ImageButton1" runat="server" CommandName="Select" ImageUrl="~/images/delete.png" onclientclick=" return confirm('Are you want to Delete this Vehicle?');" />
<asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="~/images/refre.png" CommandName="Grab" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Year" HeaderText="Year" SortExpression="Year" />
<asp:BoundField DataField="Make" HeaderText="Make" SortExpression="Make" />
<asp:BoundField DataField="Model" HeaderText="Model" SortExpression="Model" />
<asp:BoundField DataField="Submodel" HeaderText="Submodel" SortExpression="Submodel" />
<asp:BoundField DataField="ISENABLED" HeaderText="ISENABLED" SortExpression="ISENABLED" />
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<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>
Try something like this. Since you're trying to access the values in the command event and not in the OnSelectedIndexChanged event you need to get hold of the row triggering the command event first.
if (e.CommandName == "Grab")
{
GridViewRow row = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
if (row != null)
{
Label2.Text = row.Cells[2].Text;
Label3.Text = row.Cells[3].Text;
Label4.Text = row.Cells[4].Text;
Label5.Text = row.Cells[5].Text;
}
}
I have a GridView that is built from a Linq query as follows
var GridViewLoad = from d in QVuser.QlikViewDashboards.AsEnumerable()
join p in tempPermissions.AsEnumerable() on d.DashboardId equals Convert.ToInt32(p["DashboardId"])
where Convert.ToInt32(p["UserId"]) == GridViewUser
select new
{
DashboardId = d.DashboardId,
PermissionId = Convert.ToInt32(p["PermissionId"]),
DashboardName = d.DashboardName,
Operational_Unit = p["Operational_Unit"].ToString(),
Cost_Centre = p["Cost_Centre"].ToString(),
Project = p["Project"].ToString(),
Fund = p["Fund"].ToString()
};
GridView1.DataSource = GridViewLoad;
GridView1.DataKeyNames = new string[] {"PermissionId"};
GridView1.DataBind();
Then the GridView is defined as:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3"
GridLines="Vertical" ShowHeaderWhenEmpty="True" OnRowDeleting="GridView1_RowDeleting"
style="text-align: center" BackColor="White" BorderColor="#999999"
BorderStyle="None" BorderWidth="1px" Width="550px"
>
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:TemplateField HeaderText="Delete" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="false"
CommandArgument='<%# Eval("PermissionId") %>' CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PermissionId" HeaderText="ID"/>
<asp:BoundField DataField="DashboardName" HeaderText="Dashboard" ReadOnly="True" SortExpression="DashboardName" />
<asp:BoundField DataField="Operational_Unit" HeaderText="Operational_Unit" ReadOnly="True" SortExpression="Operational_Unit" />
<asp:BoundField DataField="Cost_Centre" HeaderText="Cost_Centre" ReadOnly="True" SortExpression="Cost_Centre" />
<asp:BoundField DataField="Fund" HeaderText="Fund" ReadOnly="True" SortExpression="Fund" />
<asp:BoundField DataField="Project" HeaderText="Project" ReadOnly="True" SortExpression="Project" />
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" BorderStyle="Solid" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" BorderStyle="Solid"
BorderWidth="1px" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
What I want to do is hide the PermissionId field from sight, but it obviously still needs to be there for the Delete button to work..
Can someone help me out with this?
I've tried setting Visible="false", which hides it, but then my delete button stops working..
Cheers for your help..
Since you're setting the DataKeyNames, you should be able to retrieve the permission ID from the index of the row being deleted, like so:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int permissionId = (int)GridView1.DataKeys[e.RowIndex].Value;
DoDelete(permissionId);
}
This should work whether the column is visible or not.
Try
<asp:BoundField DataField="PermissionId" HeaderText="ID" Visible="False"/>