I have two dropdownlists that are used to generate a gridview that will be edited and updated. I am lost as to why the gridview will not populate. I am enclosing the coded that I have. I have tried hiddenfields, I have parameters right now that seem to be populating correctly, I am just very confused as to why I can't see the gridview. As a caveat, I need to be able to update the certain columns in the rows either by text box or dropdownlist. If I change the query on the datasource for the gridview to bring in every row I have in the database, I can see everything and edit and update perfectly.
Here is the code first my aspx then the aspx.cs
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Annos3.aspx.cs" Inherits="SHCAnnotation.WebForm2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="dlJobName" runat="server" AutoPostBack="True"
DataSourceID="JobName" DataTextField="Name" DataValueField="Name"
style="z-index: 1; left: 25px; top: 50px; position: absolute; bottom: 257px; height: 45px; width: 242px;"
onselectedindexchanged="dlJobName_SelectedIndexChanged" >
</asp:DropDownList>
<asp:SqlDataSource ID="JobName" runat="server"
ConnectionString="<%$ ConnectionStrings:SRM_MetricConnectionString %>"
SelectCommand="SELECT DISTINCT Name FROM vw_GridviewSource WHERE (DueDt > sysdatetime()) ORDER BY Name">
</asp:SqlDataSource>
<asp:GridView ID="gvSummary" runat="server" AutoGenerateColumns = "False" AllowSorting = "true"
OnRowCancelingEdit = "CancelEdit" OnRowEditing = "EditSummary" OnRowDataBound = "RowDataBound"
OnRowUpdating = "UpdateSummary" CellPadding="4" ForeColor="#333333"
GridLines="None" DataKeyNames="AnnotationNumber, Cust, Name, AnnotationDate"
style="z-index: 1; left: 10px; top: 130px; position: absolute; height: 133px; width: 257px" >
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<columns>
<asp:CommandField ShowEditButton="true" />
<asp:TemplateField HeaderText = "Annotation Number">
<ItemTemplate>
<asp:Label ID = "lblAnno" runat="server" Text='<%# Eval("AnnotationNumber") %>'> </asp:Label>
</ItemTemplate>
<HeaderStyle Width="300px" />
<ItemStyle Width="300px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Annotation By" HeaderStyle-Width = "250">
<ItemTemplate>
<asp:Label ID = "lblAnnoBy" runat="server" Text='<%# Eval("AnnotationBy") %>' Width = "150"> </asp:Label>
</ItemTemplate>
<HeaderStyle Width="450" />
<ItemStyle Width="450" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Annotation Type">
<ItemTemplate>
<asp:Label ID = "lblAnnoType" runat="server" Text='<%# Eval("AnnotationType") %>' Width = "150"> </asp:Label>
</ItemTemplate>
<HeaderStyle Width="450px" />
<ItemStyle Width="450px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Business Unit" HeaderStyle-Width = "250">
<ItemTemplate>
<asp:Label ID = "lblBU" runat="server" Text='<%# Eval("Unit") %>' Width = "250" ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblBU" runat="server" Text='<%# Eval("Unit") %>' Visible ="false"></asp:Label>
<asp:DropDownList ID = "dlBU" runat="server" AutoPostBack = "true">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle Width="300px" HorizontalAlign="Center" />
<ItemStyle Width="300px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Error Type" HeaderStyle-Width = "250">
<ItemTemplate>
<asp:Label ID = "lblET" runat="server" Text='<%# Eval("ErrorType") %>' Width = "250" ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblET" runat="server" Text='<%# Eval("ErrorType") %>' Visible ="false"></asp:Label>
<asp:DropDownList ID = "dlET" runat="server" AutoPostBack = "true">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle Width="300px" HorizontalAlign="Center" />
<ItemStyle Width="300px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Actual Agency Error" HeaderStyle-Width = "250">
<ItemTemplate>
<asp:Label ID = "lblAA" runat="server" Text='<%# Eval("ActualAgencyError") %>' Width = "250" ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAA" runat="server" Text='<%# Eval("ActualAgencyError") %>' Visible ="false"></asp:Label>
<asp:DropDownList ID = "dlAA" runat="server" AutoPostBack = "true">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle Width="300px" HorizontalAlign="Center" />
<ItemStyle Width="300px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "AnnotationComments">
<ItemTemplate>
<asp:Label ID = "lblAnnoComm" runat ="server" Text = '<%# Eval("AnnotationComments") %>' Width = "400"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "sgk Comments">
<ItemTemplate>
<asp:Label ID = "lblsgkComm" runat ="server" Text = '<%# Eval("sgkComments") %>' Width = "400"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Textbox ID="tbsgkComm" runat="server" Text='<%# Eval("sgkComments") %>' TextMode = "MultiLine" Columns = "40" ></asp:Textbox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center" Width="400px" />
<ItemStyle HorizontalAlign="Justify" Width="400px" />
</asp:TemplateField>
</columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
</div>
<asp:DropDownList ID="dlStage" runat="server" AutoPostBack="True"
DataSourceID="Stage" DataTextField="Annotation_Date"
DataValueField="Annotation_Date" Height="45px"
style="z-index: 1; left: 360px; top: 50px; position: absolute"
Width="240px" onselectedindexchanged="dlStage_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="Stage" runat="server"
ConnectionString="<%$ ConnectionStrings:SRM_MetricConnectionString %>"
SelectCommand="SELECT DISTINCT [AnnotationDate] AS Annotation_Date FROM [vw_GridviewSource] WHERE ([Name] = #Name)">
<SelectParameters>
<asp:ControlParameter ControlID="dlJobName" Name="Name"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:HiddenField ID = "hfJN" runat="server" />
<asp:HiddenField ID = "hfST" runat="server" />
</form>
</body>
</html>
aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Configuration;
namespace SHCAnnotation
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//hfJN.Value = dlJobName.SelectedIndex.ToString();
//hfST.Value = dlStage.SelectedIndex.ToString();
//this.BindDataInit();
}
}
protected void EditSummary(object sender, GridViewEditEventArgs e)
{
gvSummary.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvSummary.EditIndex = -1;
BindData();
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvSummary.EditIndex == e.Row.RowIndex)
{
DropDownList dlBU = (DropDownList)e.Row.FindControl("dlBU");
string Cust = gvSummary.DataKeys[e.Row.RowIndex].Values["Cust"].ToString();
string BUquery = "select distinct Unit from vw_BU where Business ='" + Cust + "'";
SqlCommand BUcmd = new SqlCommand(BUquery);
dlBU.DataSource = GetData(BUcmd);
dlBU.DataTextField = "Unit";
dlBU.DataValueField = "Unit";
dlBU.DataBind();
dlBU.Items.FindByValue((e.Row.FindControl("lblBU") as Label).Text).Selected = true;
DropDownList dlET = (DropDownList)e.Row.FindControl("dlET");
string ETquery = "select distinct ErrorType from ErrorType";
SqlCommand ETcmd = new SqlCommand(ETquery);
dlET.DataSource = GetData(ETcmd);
dlET.DataTextField = "ErrorType";
dlET.DataValueField = "ErrorType";
dlET.DataBind();
dlET.Items.FindByValue((e.Row.FindControl("lblET") as Label).Text).Selected = true;
DropDownList dlAA = (DropDownList)e.Row.FindControl("dlAA");
string AAquery = "select distinct AAA from ActualAgencyError";
SqlCommand AAcmd = new SqlCommand(AAquery);
dlAA.DataSource = GetData(AAcmd);
dlAA.DataTextField = "AAA";
dlAA.DataValueField = "AAA";
dlAA.DataBind();
dlAA.Items.FindByValue((e.Row.FindControl("lblAA") as Label).Text).Selected = true;
}
}
protected void UpdateSummary(object sender, GridViewUpdateEventArgs e)
{
string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
string ET = (gvSummary.Rows[e.RowIndex].FindControl("dlET") as DropDownList).SelectedItem.Value;
string AA = (gvSummary.Rows[e.RowIndex].FindControl("dlAA") as DropDownList).SelectedItem.Value;
string AnnotationNumber = gvSummary.DataKeys[e.RowIndex].Value.ToString();
string sgkComments = (gvSummary.Rows[e.RowIndex].FindControl("tbsgkComm") as TextBox).Text;
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
string query = "update vw_GridviewSource set [BusinessUnit] = #BU, [ErrorType] = #ET, [sgkComments] = #sgk, [ActualAgencyError] = #AA where [AnnotationNumber] = #AnnoNum";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#BU", BU);
cmd.Parameters.AddWithValue("#AnnoNum", AnnotationNumber);
cmd.Parameters.AddWithValue("#ET", ET);
cmd.Parameters.AddWithValue("#AA", AA);
cmd.Parameters.AddWithValue("#sgk", sgkComments);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
private void BindDataInit()
{
SqlCommand cmd = new SqlCommand();
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.Connection = con;
cmd.CommandText = "select [AnnotationNumber],[AnnotationBy],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust,Name,AnnotationDate from vw_GridviewSource" ;
gvSummary.DataSource = GetData(cmd);
gvSummary.DataBind();
}
private void BindData()
{
string selectedName = dlJobName.SelectedValue;
string selectedStage = dlStage.SelectedValue;
//SqlCommand cmd = new SqlCommand(query);
SqlCommand cmd = new SqlCommand();
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.Connection = con;
cmd.CommandText = "select [AnnotationNumber],[AnnotationBy],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust,Name,AnnotationDate from vw_GridviewSource where Name = #p1 and AnnotationDate = #p2";
//cmd.Parameters.AddWithValue("#p1",selectedName);
//cmd.Parameters.AddWithValue("#p2",selectedStage);
gvSummary.DataSource = GetData(cmd);
gvSummary.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string selectedName = dlJobName.SelectedValue;
string selectedStage = dlStage.SelectedValue;
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#p1",selectedName);
cmd.Parameters.AddWithValue("#p2",selectedStage);
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
protected void dlJobName_SelectedIndexChanged(object sender, EventArgs e)
{
//string JobName = Application["gJob"].ToString();
BindData();
}
protected void dlStage_SelectedIndexChanged(object sender, EventArgs e)
{
//string stage = Application["gStage"].ToString();
BindData();
}
}
}
Related
I am trying to export gridview data with image to pdf. I have used relative path while saving the image to project directory,but i have to manually include every pic into project.I get the above error during html parsing.I am a newbie and trying to learn on my own.Kindly show some light into where i went wrong.My code is given below:
namespace BudgetApp
{
public partial class display : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
/*protected string GetUrl(string page)
{
string[] splits = Request.Url.AbsoluteUri.Split('/');
if (splits.Length >= 2)
{
string url = splits[0] + "//";
for (int i = 2; i < splits.Length - 1; i++)
{
url += splits[i];
url += "/";
}
return url + page;
}
return page;
}*/
public override void VerifyRenderingInServerForm(Control control)
{
//
}
protected void btnPdf_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
}
}
My aspx page:
<body>
<h1 style="text-align:center">Monthly Budget Analysis</h1>
<br /><br />
<div id="wrap">
<div class="well">
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" >
<asp:ListItem>January</asp:ListItem>
<asp:ListItem>February</asp:ListItem>
<asp:ListItem>March</asp:ListItem>
<asp:ListItem>April</asp:ListItem>
<asp:ListItem>May</asp:ListItem>
<asp:ListItem>June</asp:ListItem>
<asp:ListItem>July</asp:ListItem>
<asp:ListItem>August</asp:ListItem>
<asp:ListItem>September</asp:ListItem>
<asp:ListItem>October</asp:ListItem>
<asp:ListItem>November</asp:ListItem>
<asp:ListItem>December</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" Height="267px" Width="913px" ShowHeaderWhenEmpty="True" UseAccessibleHeader="False" EmptyDataText="Oops!!No record found">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="month" HeaderText="Month" SortExpression="month" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="expense" HeaderText="Expense" SortExpression="expense" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="budget" HeaderText="Budget" SortExpression="budget" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="balance" HeaderText="Balance" SortExpression="balance" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderText="Bill" SortExpression="bill">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("bill") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height="100px" ImageUrl='<%# Eval("bill")%>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:BudgetConnectionString8 %>" SelectCommand="SELECT * FROM [details] WHERE ([month] = #month)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="month" PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<asp:Button ID="btnPdf" runat="server" Text="Export to Pdf" OnClick="btnPdf_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</div>
</div>
</body>
Code to save data into database:
namespace BudgetApp
{
public partial class _new : System.Web.UI.Page
{
static String imagelink;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("display.aspx");
}
protected void submit_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page,this.Page.GetType(), "script", "<script type='text/javascript'>Budget();</script>", false);
SqlConnection conn = new SqlConnection(#"Data Source=co\sqlexpress;Initial Catalog=Budget;Integrated Security=true");
conn.Open();
if (file1.HasFile == true)
{
String contenttype = file1.PostedFile.ContentType;
if (contenttype == "image/jpeg")
{
string f=Path.GetFileName(file1.PostedFile.FileName);
file1.SaveAs(HttpContext.Current.Server.MapPath(#"~/saveimg/"+ f));
imagelink = "~/saveimg/" + file1.FileName;
}
}
int a = Convert.ToInt32(exp.Text);
int b = Convert.ToInt32(budget.Text);
int balance = b - a;
SqlCommand obj = new SqlCommand("insert into details values('" + ddlmonth.SelectedValue + "','" + exp.Text + "','" + budget.Text + "','" + balance + "','" + imagelink + "')", conn);
obj.ExecuteNonQuery();
conn.Close();
}
}
}
UPDATE:
I added a new button to give print functionality using javascript,and when the print page popped up ,i selected save as pdf and the image is also getting rendered :)
But i wish i could directly save it to pdf on a button click.My code for printing below:
<script type="text/javascript">
function PrintGridData() {
var prtGrid = document.getElementById('<%=GridView1.ClientID %>');
var prtwin = window.open('', 'PrintGridView',
'left=100,top=100,width=400,height=400,tollbar=0,scrollbars=1,status=0,resizable=1');
prtwin.document.write(prtGrid.outerHTML);
prtwin.document.close();
prtwin.focus();
prtwin.print();
prtwin.close();
}
</script>
<asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick="PrintGridData();"/>
i have a gridview in which in every row there is a checkbox and a linkbutton..when i will check the checkbox i want to get the text of the checkboxes..but by my code i am getting null in the text of the linkbutton...
my code
<asp:GridView ID="GridView5" AutoGenerateColumns = "False" runat="server" onpageindexchanging = "GridView1_PageIndexChanging" AllowPaging="True" BackColor="White" BorderColor="White" BorderWidth="2px" CellPadding="3" PageSize="6" BorderStyle="Ridge" CssClass="grid" CellSpacing="1" GridLines="None" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="FileCheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contest Name">
<ItemTemplate>
<asp:LinkButton Text='<%#Eval("Contest Name")%>' PostBackUrl='<%# String.Format("Dynamic.aspx?ID=3&filepath={0}", Eval("Contest Name") ) %>' runat="server" />
</ItemTemplate>
<ItemStyle Width="250px" CssClass="itemstyle"></ItemStyle>
</asp:TemplateField>
</asp:GridView>
where i am retrieving the text
for (int i = 0; i < GridView5.Rows.Count; i++)
{
CheckBox chk = (CheckBox)GridView5.Rows[i].FindControl("FileCheckBox");
if (chk.Checked == true)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
string probname = GridView5.Rows[i].Cells[1].Text.ToString();
}
}
here i am getting the string of probname as null??
Simple
Just Replace Your Check box code inside template field with
<asp:CheckBox ID="FileCheckBox" AutoPostBack="True" OnCheckedChanged="someMethod" Text='<%#Eval("Names") %>' runat="server" />
and add this on Server Side
protected void someMethod(object sender, EventArgs e)
{
foreach (GridViewRow item in GridView5.Rows)
{
CheckBox chk = (CheckBox)item.FindControl("FileCheckBox");
if (chk.Checked == true)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
string probname = chk.Text;
}
}
}
My scenario is : I have one dataGrid with 5-6 columns. i have 3 filters which use 3 SQL queries methods in codeBehind :SearchByName(), SearchByValue() , SearchByDate().I have fourth method show DefaultShow() which display all data without any filters.
Basicly I want when Page is loaded DefaultShow() method to load and then user can choose option for search with RadioButtonList
DefaultShow() code is :
public void DefaultShow()
{
string connectionString = cs.getConnection();
string query = "select Id ,name,value,Description,DateCreate from AllCostView where IdUser = '" + cui.getCurrentId() + "'";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand command = new SqlCommand(query, myConnection);
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(command);
using (DataTable myDataTable = new DataTable())
{
mySqlAdapter.Fill(myDataTable);
GridViewCost.DataSource = myDataTable;
GridViewCost.DataBind();
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
DefaultShow();
}
But this not work what am I miss?
My gridViewCode is this :
<div class ="gridView">
<asp:GridView ID="GridViewCost" runat="server" AutoGenerateColumns="False" CaptionAlign="Top"
ShowFooter="True" ShowHeaderWhenEmpty="True" Font-Overline="False"
Font-Strikeout="False" Font-Underline="False"
AllowPaging="true"
PageSize="5"
CssClass="mGrid"
PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt" OnPageIndexChanging="GridViewCost_PageIndexChanging" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged" >
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
<Columns>
<asp:BoundField DataField="Id" HeaderText="Номер" />
<asp:TemplateField HeaderText="Име">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
<ControlStyle Width="100px" />
</asp:TemplateField>
<asp:BoundField DataField="Value" HeaderText="Стойност" />
<asp:BoundField DataField="Description" HeaderText="Описание" />
<asp:BoundField DataField="DateCreate" HeaderText="Дата" />
</Columns>
<AlternatingRowStyle />
<HeaderStyle HorizontalAlign="Right"/>
<PagerStyle />
<RowStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" HorizontalAlign="Center" />
</asp:GridView>
If it's needed i will post more code . Thanks.
I have four text-boxes, two buttons one grid-view and one check-box and i put require field validation on each text-box i have a database so that when i enter value in the text-boxes and press submit button data store in the database and show in gird as i use datatable. i Have edit, delete and update link in my grid-view now when i click on edit or delete link validation error message displayed and i won't make changes in my grid. can any one help me on this.
Thanks in advance
My aspx code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="height: 191px">
<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
<td class="style3">
FirstName</td>
<td>
<asp:TextBox ID="tFirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="tFirstName" ErrorMessage="Enter First Name">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style3">
Last name</td>
<td>
<asp:TextBox ID="tLastName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="tLastName" ErrorMessage="Enter Last Name">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style3">
Age</td>
<td>
<asp:TextBox ID="tAge" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="tAge" ErrorMessage="" dalega">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style7">
Is Active</td>
<td class="style8">
<asp:CheckBox ID="dropActive" runat="server" />
</td>
</tr>
<tr>
<td class="style3">
Auto ID</td>
<td>
<asp:TextBox ID="autoID" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
ControlToValidate="autoID" ErrorMessage="Marzi hai teri">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style6">
</td>
<td class="style5">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Sumit" ValidationGroup="abc"/>
<input type="reset" />
<br />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" Height="72px" />
</td>
</tr>
<tr>
<td class="style4" colspan="2">
<asp:Label ID="lblMessage" runat="server" ForeColor="Green" EnableViewState="false" />
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="false" Width="36%" OnRowEditing="EditRow" OnRowCancelingEdit="CancelEditRow" OnRowUpdating="UpdateRow" DataKeyNames="AutoId" OnRowDeleting="DeleteRow" AllowPaging="true" OnPageIndexChanging="ChangePage" AllowSorting="True">
<Columns>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update" />
<asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="AutoId" DataField="AutoId" ReadOnly="true" />
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<%# Eval("FirstNAme") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName") %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<%# Eval("LastName") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<%# Eval("Age") %></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age") %>' Columns="3" />
<asp:RequiredFieldValidator ID="REw" runat="server" ControlToValidate="txtAge" Text="*" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
<EditItemTemplate>
<asp:DropDownList ID="dropActive" runat="server" SelectedValue='<%# Eval("Active") %>'>
<asp:ListItem Text="Yes" Value="True" />
<asp:ListItem Text="No" Value="False" />
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to delete?')">
<asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#efefef" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
</table>
</div>
</form>
</body>
</html>
code for aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateData();
}
}
protected void EditRow(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.PopulateData();
}
protected void CancelEditRow(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
this.PopulateData();
}
protected void DeleteRow(object sender, GridViewDeleteEventArgs e)
{
var autoID = GridView1.DataKeys[e.RowIndex].Value;
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=EMS;Integrated Security=True"))
{
string sql = "Delete from PersonalDetail" +" where AutoId = #AutoId";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#AutoId", autoID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text ="Record has been deleted successfully !";
lblMessage.ForeColor = System.Drawing.
Color.Red;
this.PopulateData();
}
protected void ChangePage(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.PopulateData();
}
protected void UpdateRow(object sendedr, GridViewUpdateEventArgs e)
{
var autoID = GridView1.DataKeys[e.RowIndex].Value;
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
TextBox tFirstName = row.FindControl("txtFirstName") as TextBox;
TextBox tLastName = row.FindControl("txtLastName") as TextBox;
TextBox tAge = row.FindControl("txtAge") as TextBox;
DropDownList dropActive = row.FindControl("dropActive") as DropDownList;
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=EMS;Integrated Security=True"))
{
string sql = "Update PersonalDetail set FirstName = #FirstName,LastName=#LastName, Age= #Age, Active = #Active" + " where AutoId = #AutoId";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#FirstName", tFirstName.Text.Trim());
cmd.Parameters.AddWithValue("#LastName", tLastName.Text.Trim());
cmd.Parameters.AddWithValue("#Age", tAge.Text.Trim());
cmd.Parameters.AddWithValue("#Active", dropActive.SelectedValue);
cmd.Parameters.AddWithValue("#AutoId", autoID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
lblMessage.Text ="Record updated successfully !";
GridView1.EditIndex = -1;
this.PopulateData();
}
private void PopulateData()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=EMS;Integrated Security=True"))
{
string sql = "Select * from PersonalDetail";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=EMS;Integrated Security=True");
con.Open();
string FirstName = tFirstName.Text;
string LastName = tLastName.Text;
string Age = tAge.Text;
string Active = dropActive.Text;
string AutoId = autoID.Text;
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "insert into PersonalDetail(FirstName,LastName,Age,Active,AutoId) values('" + FirstName + "','" + LastName + "','" + Age + "','" + Active + "','" + AutoId + "')";
cmd.Parameters.AddWithValue("#FirstName", tFirstName.Text.Trim());
cmd.Parameters.AddWithValue("#LastName", tLastName.Text.Trim());
cmd.Parameters.AddWithValue("#Age", tAge.Text.Trim());
cmd.Parameters.AddWithValue("#Active", dropActive.Text.Trim());
cmd.Parameters.AddWithValue("#AutoId", autoID.Text.Trim());
cmd.ExecuteNonQuery();
}
con.Close();
tFirstName.Text = string.Empty;
tLastName.Text = string.Empty;
tAge.Text = string.Empty;
dropActive.Text = string.Empty;
tFirstName.Focus();
}
None of your Validation control has a Validation Group.
Add this to all your RequiredFieldValidator.
ValidationGroup="SomeName"
Make sure all your RequiredFieldValidator has the same ValidationGroup
Now finally add the ValidationGroup="SomeName" to your Button control which when clicked raises the Validation controls.
I just use this.populate(); on button1 to show grid-view after enter details in the text-boxes thanks for your reply guys.
Try removing validation checking from your link CauseValidation="false"
<ItemTemplate>
<asp:LinkButton CauseValidation="false" ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
I have defined a nested grid view in the following way.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" GridLines="None">
<Columns>
<asp:BoundField DataField="Date Of Transaction" HeaderText="Date Of Transaction"
SortExpression="Date Of Transaction" />
<asp:BoundField DataField="Invoice Number" HeaderText="Invoice Number" SortExpression="Invoice Number" />
<asp:BoundField DataField="totalAmount" HeaderText="totalAmount" ReadOnly="True"
SortExpression="totalAmount" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" ShowHeader="false" GridLines="None" OnRowDataBound="gridView2_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="Btn1" runat="server" Text="Download" OnClick="Btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ComponentDBConnectionString %>"
SelectCommand="SelectUserPreviousHistory" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="XYZZ" Name="userName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
The screenshot of the output is here. As you can see i have a "Download" button in each row of the child gridview (i.e., gridView2) but I want the download button to be last column but .net is rendering it to be the first column.
How can I do it?
More over gridview2 datasource is arraylist. Here is the code
gridView2.DataSource = titlesArrayList;
gridView2.DataBind();
Please help me
Thanks in anticipation
Why don't you simply add a Label before the Donwload-Button in the ItemTemplate? You could set the Label's Text in RowDataBound(gridView2_DataBound).
Edit: to show the header columns of the nested gridview in the header of the outer gridview, you could set ShowHeader="false" in the inner grid and use a HeaderTemplate with two labels for "Software Titles" and "Download here" and appropriate CSS-Styles to fit to the inner grid.
Edit:
Here is a working test-page. Pick the parts you didn't understand:
aspx:
<asp:GridView ID="GrdTransaction" runat="server" OnRowDataBound="GrdTransaction_RowDataBound" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="DateOfTransaction" HeaderText="Date Of Transaction"
SortExpression="DateOfTransaction" />
<asp:TemplateField>
<HeaderTemplate>
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td><asp:Label ID="LblFileNameHeader" Text="File-Name" runat="server" /></td><td><asp:Label ID="LblDownloadHeader" Text="Download file" runat="server" /></td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<asp:GridView ID="GrdDocument" runat="server" ShowHeader="false" GridLines="None" AutoGenerateColumns="false"
OnRowCommand="GrdDocument_RowCommand" OnRowDataBound="GrdDocument_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label ID="LblFileName" Text='<%# Eval("Doc")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="BtnDownload" runat="server" CommandArgument='<%# Eval("Doc")%>' CommandName="Download" Text="Download" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Codebehind(converted from vb.net to c#):
public class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
this.GrdTransaction.DataSource = GetOuterGridSource();
this.GrdTransaction.DataBind();
}
}
private DataTable GetOuterGridSource()
{
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("DateOfTransaction", typeof(DateTime)));
DataRow row = tbl.NewRow();
row["ID"] = 1;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
return tbl;
}
private DataTable GetNestedGridSource()
{
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Doc", typeof(string)));
DataRow row = tbl.NewRow();
row["ID"] = 1;
row["Doc"] = "Smart Defrag";
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["Doc"] = "Visio Viewer";
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["Doc"] = "Rapid Typing";
tbl.Rows.Add(row);
return tbl;
}
protected void GrdTransaction_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
dynamic row = ((DataRowView)e.Row.DataItem).Row;
dynamic GrdDocument = (GridView)e.Row.FindControl("GrdDocument");
GrdDocument.DataSource = GetNestedGridSource();
GrdDocument.DataBind();
GrdDocument.RowCommand += GrdDocument_RowCommand;
}
}
protected void GrdDocument_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
dynamic row = ((DataRowView)e.Row.DataItem).Row;
dynamic LblFileName = (Label)e.Row.FindControl("LblFileName");
LblFileName.Text = row("Doc").ToString;
}
}
protected void GrdDocument_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "Download") {
dynamic docName = e.CommandArgument.ToString();
}
}
public WebForm1()
{
Load += Page_Load;
}
}
I have set the LblFileName's Text poperty in GrdDocument_RowDataBound. That is redundant because i've always used eval on the aspx-page. I wanted to show both ways for the sake of completeness.
This is result:
in your gridView2, set AutoGenerateColumns="False" and add a asp:BoundField before the asp:TemplateField
Are you sure there is no missing code in your snippet?
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" ShowHeader="false" GridLines="None" OnRowDataBound="gridView2_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="" DataField="ToString" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="Btn1" runat="server" Text="Download" OnClick="Btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>