I have some doubt
This is my coding for aspx page and .cs page
How can I achieve the following
If i select February the header text assigned January value and i select march then assign February value...Could you please help me find a solution for it
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" >
<Columns>
<asp:TemplateField HeaderText="8-14">
<ItemTemplate>
<asp:TextBox ID="TxtWeek2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In .CS page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.Items.Add("Select");
DropDownList1.Items.Add("January");
DropDownList1.Items.Add("February");
DropDownList1.Items.Add("March");
DropDownList1.Items.Add("April");
DropDownList1.Items.Add("May");
SqlConnection cn = new SqlConnection("Data Source=192.169.10.22;Initial Catalog=SHRICITYUNO;User ID=uno;Password=uno");
SqlCommand cmd = new SqlCommand();
cn.Open();
cmd = new SqlCommand("SELECT Week1 FROM Finman_FundPlan", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string s = DropDownList1.SelectedItem.Text.ToString();
if (DropDownList1.SelectedItem.Text == "January")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
else if (DropDownList1.SelectedItem.Text == "February")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "-";
}
else if (DropDownList1.SelectedItem.Text == "March")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
else if (DropDownList1.SelectedItem.Text == "April")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-30";
}
else if (DropDownList1.SelectedItem.Text == "May")
{
this.GridView1.Columns[0].HeaderText = "";
this.GridView1.Columns[0].HeaderText = "29-31";
}
}
you can do it using Javascript at client side.
if you observe the grid view then you can notice that row[0] is the header row for gridview.
now you can check decide the which cell test you have to change.
see the following javascript function to accomplish your task
<script language="Javascript">
function ChangeHeaderText()
{
var gridObject = document.getElementById("Gridview1");
gridObject.rows[0].cells[0].innerText = 'NewHeader Text';
return false;
}
</script>
//call above function on 'onchange' event of dropdownlist
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" onchange = "return ChangeHeaderText()"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Try this It will work......
Related
I have created gridview. Added a textbox to specify what number of columns user want to add to the grid dynamically and its done successfully.
I want to add text box to the dynamically added fields to enter the data and save it to the database(I am able to add text fields to the rows and save data) but i didnt got any solution yet.
I have tried with itemplate but I don't know much about it. i have added my code below.
Here is my aspx code
<input type="hidden" runat="server" value="0" id="columnAdded"/>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<%--<asp:CommandField ShowEditButton="True" />--%>
<asp:TemplateField HeaderText="S. No.">
<ItemTemplate>
<asp:Label ID="lblsno" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lbInsert" runat="server">Insert</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Parts" DataField="parts">
</asp:BoundField>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder_InputControl" runat="server" ></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>--%>
<%--<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnedit" runat="server" Text="Edit" CommandName="EditRow"/>
</ItemTemplate>
</asp:TemplateField>--%>
</Columns>
</asp:GridView>
and here is .cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
drpstation.Items.Clear();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from stationdesc where stndesc <> '' and id is not null";
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "stationdesc");
drpstation.DataSource = ds.Tables[0];
drpstation.DataTextField = ds.Tables[0].Columns["stndesc"].ColumnName.ToString();
drpstation.DataValueField = ds.Tables[0].Columns["id"].ColumnName.ToString();
drpstation.DataBind();
drpstation.Items.Insert(0, new ListItem("Select Station", "0"));
}
catch (Exception ex)
{
string Msg = "select station error";
Msg += ex.Message;
}
finally
{
con.Close();
}
}
if (!IsPostBack)
{
griddisplay();
}
}
public void griddisplay()
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM stnparts", con);
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
//DataTable dt = new DataTable();
//dt.Columns.Add("Parts", typeof(string));
//DataRow drr = dt.NewRow();
//drr["Parts"] = "Weldmet";
//dt.Rows.Add(drr);
//drr = dt.NewRow();
//drr["Parts"] = "MFG Parts";
//dt.Rows.Add(drr);
//GridView1.DataSource = dt;
//GridView1.DataBind();
}
catch (Exception d)
{
string message = "grid error";
message += d.Message;
}
finally
{
con.Close();
}
}
protected void btnadd_Click(object sender, EventArgs e)
{
int num;
num = Convert.ToInt32(txtnumber.Text.Trim());
int addedColumn = Convert.ToInt32(columnAdded.Value);
for (int i = addedColumn + 1; i <= addedColumn + num; i++)
{
string name = "Unit";
name = string.Concat(name, i);
TemplateField test = new TemplateField();
test.HeaderText = name;
GridView1.Columns.Add(test);
TextBox txtname = new TextBox();
string txtunit = "txtunit";
txtname.ID = txtunit + i;
}
griddisplay();
columnAdded.Value = (addedColumn + num).ToString();
}
public class TemplateHandler : ITemplate
{
void ITemplate.InstantiateIn(Control container)
{
TextBox txtbox = new TextBox();
txtbox.Text = "test";
txtbox.DataBinding += Txtbox_Binding;
container.Controls.Add(txtbox);
}
private void Txtbox_Binding(object sender, EventArgs e)
{
//throw new NotImplementedException();
TextBox txttest = (TextBox)sender;
GridViewRow container = (GridViewRow)txttest.NamingContainer;
//txttest.Text = ((TableNameClass)container.DataItem).SkillText;
((DataRowView)container.DataItem)["SkillText"].ToString();
}
}
Please help
Just a pseudo/sample code(not tested!) based on the code you posted, to give you some heads-up
protected void btnadd_Click(object sender, EventArgs e)
{
int num;
num = Convert.ToInt32(txtnumber.Text.Trim());
int addedColumn = Convert.ToInt32(columnAdded.Value);
for (int i = addedColumn + 1; i <= addedColumn + num; i++)
{
string name = "Unit";
name = string.Concat(name, i);
TemplateField test = new TemplateField();
test.HeaderText = name;
test.ItemTemplate = new TemplateHandler (); // ** This line to set ItemTemplate is missing in the code you posted
GridView1.Columns.Add(test);
// ... Other code as you need
}
}
Hope this help you.
I have two labels (label4 and label5) where the text is retrieved from data stored in column b and column c of a table (tblp). The labels are present inside the repeater control, and now on the basis of data stored in column d of same table, I am trying to show and hide the text of label4 and label5 on page load with the following rules:
If the column d consists letter s then both label text should be visible.
If the column d consists letter h then both label text should be invisible.
If the column d consists letter u then both label text should be visible.
The problem is that when trying to use the label as an argument for the method I have made, the label shows error.
Code samples of what I have done are given below.
HTML
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%#Eval("b") %>'></asp:Label>
<asp:Label ID="Label5" runat="server" Text='<%#Eval("c") %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = j.getentry(Label4.Text, Label5.Text);
if (dt.Rows.Count>0)
{
if (dt.Rows[0]["d"].ToString() == "s")
{
DataTable dp = j.getall();
if (dp.Rows.Count > 0)
{
Repeater1.DataSource = dt; /*To show text*/
Repeater1.DataBind();
}
}
else if (dt.Rows[0]["d"].ToString() == "h")
{
Label4.Visible = false;
Label5.Visible = false; /*To hide text*/
}
else if (dt.Rows[0]["d"].ToString() == "u")
{
DataTable dp = j.getall();
if (dp.Rows.Count > 0)
{
Repeater1.DataSource = dt; /*To show text*/
Repeater1.DataBind();
}
}
}
}
Method used
public DataTable getentry(string b, string c)
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);
string sql = "select *from tblp where b=#b and c=#c ";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#b", b);
cmd.Parameters.AddWithValue("#c", c);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
public DataTable getall()
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);
string sql = "select a,b,c from tblp";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dp = new DataTable();
da.Fill(dp);
return dp;
}
Another solution is
1.Put a HiddenField inside repeater and use Repeater_ItemDataBound like this
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<asp:HiddenField runat="server" ID="hidd1" Value='<%#Eval("d") %>' />
<asp:Label ID="Label4" runat="server" Text='<%#Eval("b") %>'></asp:Label>
<asp:Label ID="Label5" runat="server" Text='<%#Eval("c") %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
use Repeater1_ItemDataBound to iterate through each Repeater Item and by checking condition set the visibility to true or false
Update : since you are stroing column D values to Hidden field there is no need to compare your values like this (dt.Rows[0]["d"].ToString() == "h")
You can directly compare values stored in hiddenfield on each item binding
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
string hidd1 = ((HiddenField)(e.Item.FindControl("hidd1"))).Value; // find hidden field
Label l1 = (Label)(e.Item.FindControl("Label4"));// find lable4 value
Label l2 = (Label)(e.Item.FindControl("Label4"));//// find lable5 value
if (hidd1.ToLower == "s")// your conditon
{
l1.Visible = true;// your code1
l2.Visible = true;
}
else if (hidd1.ToLower == "h")
{
l1.Visible = false;// your code2
l2.Visible = false;
}
else
{
// defalut
}
}
if you still have some doubt read more about Repeater.ItemDataBound Event here
you can use Visible attribute
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Visible='<%# Convert.ToBoolean(Eval("SomeCondition")) %>' Text='<%#Eval("b") %>'></asp:Label>
<asp:Label ID="Label5" runat="server" Visible='<%# Convert.ToBoolean(Eval("SomeCondition")) %>' Text='<%#Eval("c") %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
try this
else if (dt.Rows[0]["d"].ToString() == "h")
{
(Label)(Repeater1.FindControl("Label4")).Visible = false;
(Label)(Repeater1.FindControl("Label5")).Visible = false; /*To hide text*/
}
I want to show a table when a SelectedValue of my DropDownList ddlKlasse is true. I'm using asp.net empty web forms with a masterpage.
The idea is:
when ddlKlasse.SelectedValue = "2" table tblDubbelTwee must be shown
when ddlKlasse.SelectedValue = "5" table tblVierMet must be shown
when ddlKlasse.SelectedValue = "9" table tblAchtMet must be shown
I get the values in my dropdownlist from my database.
The code I have now is:
In my Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
BindDropDownListKlasse();
BindDropDownListVereniging();
if (!Page.IsPostBack)
{
tblDubbelTwee.Visible = false;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
}
}
For binding the dropdown:
private void BindDropDownListKlasse()
{
try
{
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "SELECT DISTINCT AantalDeelnemers, Naam FROM Klasse;";
com.Connection = conn;
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
da.Fill(dt);
ddlKlasse.DataSource = dt;
ddlKlasse.DataValueField = "AantalDeelnemers";
ddlKlasse.DataTextField = "Naam";
ddlKlasse.DataBind();
conn.Close();
//Adding "Kies de klasse" optie in dropdownlist voor validatie
ddlKlasse.Items.Insert(0, new ListItem("Kies de klasse", "0"));
}
}
}
catch
{
}
}
For showing the tables:
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
ListItem selectedListItemDubbelTwee = ddlKlasse.Items.FindByValue("2");
if (selectedListItemDubbelTwee != null)
{
selectedListItemDubbelTwee.Selected = true;
tblDubbelTwee.Visible = true;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
};
ListItem selectedListItemVierMet = ddlKlasse.Items.FindByValue("5");
if (selectedListItemVierMet != null)
{
selectedListItemVierMet.Selected = true;
tblVierMet.Visible = true;
tblDubbelTwee.Visible = false;
tblAchtMet.Visible = false;
};
ListItem selectedListItemAchtMet = ddlKlasse.Items.FindByValue("9");
if (selectedListItemAchtMet != null)
{
selectedListItemAchtMet.Selected = true;
tblAchtMet.Visible = true;
tblDubbelTwee.Visible = false;
tblVierMet.Visible = false;
};
}
My DropDownList:
<div class="form-inline">
<div class="form-group">
<asp:DropDownList ID="ddlKlasse" class="form-control" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlKlasse_SelectedIndexChanged"></asp:DropDownList>
</div>
</div>
One of my tables:
<asp:Table ID="tblDubbelTwee" runat="server" class="table">
<asp:TableHeaderRow>
<asp:TableHeaderCell>Naam</asp:TableHeaderCell>
<asp:TableHeaderCell>Email</asp:TableHeaderCell>
<asp:TableHeaderCell>Lidmaatschapsnr</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtNaam" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtEmail" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtLidmaatschapsnr" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>
<asp:TextBox ID="txtNaam2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtEmail2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="txtLidmaatschapsnr2" type="text" class="form-control" runat="server"></asp:TextBox>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
But when I run my project and select a field in my DropDownList it gives the error: System.Web.HttpException: Selecting multiple items in a DropDownList is not allowed.
Can you please help me to solve this problem?
Your current handler for DDL index change is doing something very different from what you have described. It basically checks if the list item exists in the ddl list (no matter selected or not) and then tries to select it. Since all of 3 items exist, you are effectively trying to select 3 items, which is not allowed.
What you might be looking for is a switch by selected value:
switch (ddlKlasse.SelectValue)
{
case "2":
tblDubbelTwee.Visible = true;
tblVierMet.Visible = false;
tblAchtMet.Visible = false;
break;
case "5": //similar here
case "9": //similar here
default:
// exception or something
}
refere this code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindgrid();
}
}
void bindgrid()
{
con.Open();
SqlCommand cmd = new SqlCommand("select DISTINCT Class from addmitionform1", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlclass.DataSource = ds;
ddlclass.DataTextField = "Class";
ddlclass.DataValueField = "Class";
ddlclass.DataBind();
ddlclass.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
string id = (ddlclass.SelectedValue.ToString());
con.Close();
SqlDataAdapter da1 = new SqlDataAdapter("Select id,FirstName from addmitionform1 where Class= '" + id + "'", con);
//SqlDataAdapter da1 = new SqlDataAdapter("Select * from addmitionform1 ", con);
DataSet ds1 = new DataSet();
da1.Fill(ds1);
GridView1.DataSource = ds1;
GridView1.DataBind();
}
First move BindDropDownListKlasse() and BindDropDownListVereniging() inside if (!IsPostBack), as HarveySpecter suggested.
And change ddlKlasse_SelectedIndexChanged() to:
protected void ddlKlasse_SelectedIndexChanged(object sender, EventArgs e)
{
bool showDubbelTwee = false, showVierMet = false, showAchtMet = false;
switch (ddlKlasse.SelectedValue)
{
case "2":
showDubbelTwee = true;
break;
case "5":
showVierMet = true;
break;
case "9":
showAchtMet = true;
break;
}
tblAchtMet.Visible = showVierMet;
tblDubbelTwee.Visible = showDubbelTwee;
tblVierMet.Visible = showVierMet;
}
What you are doing now in ddlKlasse_SelectedIndexChanged() is check for each value if it's present in the dropdown, and if present select it and show the respective table.
Instead, you need to check which value is selected and show the respective table.
I have the following in my page.
2 Asp Buttons
1 GridView
1 image button for export to excel
I need to view gridview based on respective buttons. i.e. Each button will have different data to displayed. Also gridview should allow paging as there are many records. Export to excel should also happen when image button is clicked including all pages in gridview. Can any one help in this ?
My code is following
aspx file.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div>
<table id="Table2" width="100%" align="left" runat="server">
<tr>
<td class="auto-style8">
</td>
<td class="auto-style9"></td><td class="auto-style10">
<asp:Button ID="Admin" runat="server" Text="Admin" TOOLTIP="Sign In" TABINDEX="3" BackColor="Gray" BorderColor="Black" BorderStyle="Groove" Font-Bold="True" Font-Names="Arial" Font-Size="Large" ForeColor="White" Height="46px" Width="85px"/>
<asp:Menu ID="Menu1" runat="server" StaticSubMenuIndent="" Font-Bold="True" Font-Size="Large">
<Items>
<asp:MenuItem Text="Home" Value="Home" NavigateUrl="Admin_Main.aspx"></asp:MenuItem>
<asp:MenuItem Text="Add Customer" Value="Add Customer" NavigateUrl="Add_Details.aspx"></asp:MenuItem>
<asp:MenuItem Text="Delete Customer" Value="Delete Customer" NavigateUrl="Delete_Customer.aspx"></asp:MenuItem>
</Items>
</asp:Menu>
<asp:LinkButton ID="logout" runat="server" OnClick="logout_click" Font-Bold="True" Font-Size="Large">Logout</asp:LinkButton>
</td>
</tr>
</table>
</div>
<div>
<asp:Label ID="Label1" runat="server" Text="UserName" Font-Bold="True"
Font-Size="X-Large"></asp:Label>
<asp:TextBox ID="userName" Name= "userName" runat="server" Font-Bold="True"></asp:TextBox>
</div>
<div>
<asp:Button ID="Button2" runat="server" Text="Email Log" OnClick= "Email_Click" Height="35px" Font-Bold="True" Font-Size="Medium" Width="90px"/>
<asp:Button ID="Button1" runat="server" Text="All Log" Height="35px" OnClick= "Log_Click" Font-Bold="True" Font-Size="Medium" Width="90px"/>
<asp:ImageButton ID="btnexport" runat="server" Height="35px" ImageUrl="~/Images/exp-xls.gif" Width="112px" OnClick="btnExport_Click" Visible="false" />
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</asp:Content>
aspx.cs file
public partial class Display_Log : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string user = (string)(Session["user"]);
if (!IsPostBack)
{
if (user == null)
{
Response.Redirect("~/InvalidLogin.aspx");
}
else
{
Admin.Text = user;
Admin.Enabled = false;
}
}
}
protected void Email_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
cnn.ConnectionString = connStr;
cnn.Open();
String sqlSelect = String.Format(" Select Customer_Name,Time_Send_Clicked,Reminder_Type from Email_Log where Username='{0}'",userName.Text.ToString().Trim());
SqlCommand myCommand = new SqlCommand(sqlSelect, cnn);
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
cnn.Close();
btnexport.Visible = true;
}
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename=ActivityReport_" + userName.Text + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void Log_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
cnn.ConnectionString = connStr;
cnn.Open();
String sqlSelect = String.Format(" SELECT [Activity],[Time],[Ticket_Number] FROM Log where Username='{0}'", userName.Text.ToString().Trim());
SqlCommand myCommand = new SqlCommand(sqlSelect, cnn);
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
cnn.Close();
btnexport.Visible = true;
}
protected void logout_click(object sender, EventArgs e)
{
this.Session["user"] = null;
this.Session["group"] = null;
Response.Redirect("~/Default.aspx");
}
}
To add pagging u need to specify AllowPaging="True" this will add pagging but it wont work until u specify this which handle the onclick event when page button is clicked
onpageindexchanging="GridView1_PageIndexChanging"
<asp:GridView ID="GridView1"AutoGenerateColumns="false" DataKeyNames="Identityrowoftable" AllowPaging="True"
onpageindexchanging="GridView1_PageIndexChanging" />
in code behind add this
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
// you need to rebind gridview here
//just set the source and databind
}
after this the print part
first you need to clear controls so unwanted elements dont come while print.
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text =
(string)control.GetType().GetProperty("SelectedItem").
GetValue(control, null);
}
catch
{ }
control.Parent.Controls.Remove(control);
}
else if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text =
(string)control.GetType().GetProperty("Text").
GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
return;
}
how to use ClearControl when exporting as excel
protected void btnExport_Click(object sender, EventArgs e)
{
// Reference your own GridView here
if (GridView1.Rows.Count > 65535)
{
//DisplayError("Export to Excel is not allowed" +
// "due to excessive number of rows.");
return;
}
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=nameofexcelfile_" + DateTime.Now+".xls" );
Response.Charset = "";
// SetCacheability doesn't seem to make a difference (see update)
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
// Replace all gridview controls with literals
GridView1.PagerSettings.Visible = false;
ClearControls(GridView1);
System.Web.UI.HtmlControls.HtmlForm form
= new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form);
form.Controls.Add(GridView1GridView1);
form.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
this will print records without paging buttons
I am having editable Gridview with column named Country which has so long listing.
When I am showing data the value of Country is in Label but when I choose edit should show DropDownList with country listings. I am able to show listings. it should show the country selected as that was in label.
I have tried with this but dropdownlist is filled with System.Row.DataRowView also it is not set at SelectedValue given as cvalue
aspx page
<asp:TemplateField HeaderText="Country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%#Bind("Country")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCCountry" runat="server" Height="21px" Style="margin-left: 0px"
Width="194px">
<asp:ListItem Value="-1">Select..</asp:ListItem>
<asp:ListItem Value="af">Afghanistan</asp:ListItem>
<asp:ListItem Value="ax">Aland Islands</asp:ListItem>
<asp:ListItem Value="al">Albania</asp:ListItem>
</asp:DropDownList>
<EditItemTemplate>
.cs file
void gvhoteldetail_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
string cnm="",cvalue="";
string getCountry = "Select * from tbl_countrynames where `Name`='" + cname + "'";
string getCountrynames = "Select * from tbl_countrynames";
MySqlConnection con = new MySqlConnection(connection);
MySqlCommand cmd1 = new MySqlCommand(getCountrynames, con);
DataSet ds1 = new DataSet();
MySqlDataAdapter da1 = new MySqlDataAdapter(cmd1);
da1.Fill(ds1);
MySqlCommand cmd = new MySqlCommand(getCountry, con);
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
cnm = ds.Tables[0].Rows[0]["Name"].ToString();
cvalue = ds.Tables[0].Rows[0]["Value"].ToString();
}
DropDownList ddlcountry = (DropDownList)e.Row.FindControl("ddlCCountry");
ddlcountry.DataSource = ds1;
ddlcountry.SelectedValue = cvalue;
ddlcountry.DataBind();
}
What could be wrong?
This worked for me. When populating the GridView, you should populate each DropDownList in the RowDataBound event:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
numberFormatDA formatDA = new numberFormatDA();
DataTable mytable = new DataTable();
DataColumn formatIDcolumn = new DataColumn("fkNumberFormat");
DataColumn formatNameColumn = new DataColumn("numberFormat");
mytable.Columns.Add(formatIDcolumn);
mytable.Columns.Add(formatNameColumn);
DataSet ds = new DataSet();
ds = formatDA.getNumberFormatsDS();
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
TextBox txtSite = (TextBox)e.Row.FindControl("txtIDSite");
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlNumberFormat");
DataRow[] rows = ds.Tables[0].Select();
foreach (DataRow row in rows)
{
DataRow newrow = mytable.NewRow();
newrow["fkNumberFormat"] = row["idnumberFormat"];
newrow["numberFormat"] = row["numberFormat"];
mytable.Rows.Add(newrow);
}
ddl.DataSource = mytable;
ddl.DataTextField = "numberFormat";
ddl.DataValueField = "fkNumberFormat";
int numberFormatID = 0;
Label lblFormatID = (Label)e.Row.FindControl("numberFormatLabel");
numberFormatID = Int32.Parse(lblFormatID.Text);
ddl.SelectedValue = numberFormatID.ToString();
ddl.DataBind();
}
}
Hope this helps!
This way you can make it work but I know there's a much better way to achieve this..
Try this for now...
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewRow gvr = GridView1.Rows[e.NewEditIndex];
Label lb = (Label)gvr.FindControl("lblCountry");
GridView1.EditIndex = e.NewEditIndex;
binddata();
getselected(lb.Text);
}
private void getselected(string text)
{
GridViewRow gvr = GridView1.Rows[GridView1.EditIndex];
DropDownList dr = (DropDownList)gvr.FindControl("ddlCCountry");
dr.SelectedIndex = dr.Items.IndexOf(dr.Items.FindByText(text));
}
protected void gvGeneralMaster_RowEditing(object sender, GridViewEditEventArgs e)
{
try
{
if (clsGeneral._strRights[2] == "0")
{
//ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ShowAlert", "ShowAlert();", true);
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowUnAuthorisedMsg", "ShowUnAuthorisedMsg();", true);
Response.Redirect("UnauthorizedUser.aspx");
}
else
{
GridViewRow gvRow = (GridViewRow)gvGeneralMaster.Rows[e.NewEditIndex];
ViewState["COUNTRY"] = ((Label)gvRow.FindControl("lblCountry")).Text.Trim();
ViewState["STATE"] = ((Label)gvRow.FindControl("lblState")).Text.Trim();
gvGeneralMaster.EditIndex = e.NewEditIndex;
GetGeneralDetails();
}
}
catch (Exception ex)
{
lblErrorMsg.Text = ex.Message.ToString();
if (!ex.Message.ToString().Contains("Thread was being aborted."))
{
//oBL_ClsLog.SaveLog(Convert.ToString(Session["CurrentUser"]).Trim(), "Exception", ex.Message.ToString(), "GROUP MASTER");
ErrMsg = ex.Message.ToString(); try { string[] arrErr = ex.Message.ToString().Split('\n'); ErrMsg = arrErr[0].ToString().Trim(); }
catch { } Response.Redirect("Error.aspx?Error=" + ErrMsg.ToString().Trim());
}
}
}
protected void gvGeneralMaster_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
if (clsGeneral._strRights[2] == "0")
{
//ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "ShowAlert", "ShowAlert();", true);
//ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "ShowUnAuthorisedMsg", "ShowUnAuthorisedMsg();", true);
Response.Redirect("UnauthorizedUser.aspx");
}
else
{
GridViewRow gvRow = (GridViewRow)gvGeneralMaster.Rows[e.RowIndex];
oPRP._GeneralCode = int.Parse(((Label)gvRow.FindControl("lblEGenCode")).Text.Trim());
oPRP._GenaralName = ((TextBox)gvRow.FindControl("txtECity")).Text.Trim();
oPRP._StateName = ((DropDownList)gvRow.FindControl("ddlEState")).SelectedItem.Text.Trim() != "SELECT" ? ((DropDownList)gvRow.FindControl("ddlEState")).SelectedItem.Text.Trim() : "";
oPRP._CountryName = ((DropDownList)gvRow.FindControl("ddlECountry")).SelectedItem.Text.Trim() != "SELECT" ? ((DropDownList)gvRow.FindControl("ddlECountry")).SelectedItem.Text.Trim() : "";
oPRP._Remarks = ((TextBox)gvRow.FindControl("txtERemarks")).Text.Trim();
oPRP._Active = ((CheckBox)gvRow.FindControl("chkEditActive")).Checked;
oPRP._ModifiedBy = Session["CurrentUser"].ToString();
oDAL.SaveUpdateGeneralMaster("UPDATE", oPRP);
gvGeneralMaster.EditIndex = -1;
GetGeneralDetails();
}
}
catch (Exception ex)
{
lblErrorMsg.Text = ex.Message.ToString();
if (!ex.Message.ToString().Contains("Thread was being aborted."))
{
//oBL_ClsLog.SaveLog(Convert.ToString(Session["CurrentUser"]).Trim(), "Exception", ex.Message.ToString(), "GROUP MASTER");
ErrMsg = ex.Message.ToString(); try { string[] arrErr = ex.Message.ToString().Split('\n'); ErrMsg = arrErr[0].ToString().Trim(); }
catch { } Response.Redirect("Error.aspx?Error=" + ErrMsg.ToString().Trim());
}
}
}
It's too late for the answer, but hope it would help someone. You can place the SelectedValue property inside your dropdownlist tag like below:
<asp:DropDownList SelectedValue='<% Eval("Country") %>' ID="ddlCCountry" runat="server" Height="21px" Style="margin-left: 0px" Width="194px">
<asp:ListItem Value="-1">Select..</asp:ListItem>
<asp:ListItem Value="af">Afghanistan</asp:ListItem>
<asp:ListItem Value="ax">Aland Islands</asp:ListItem>
<asp:ListItem Value="al">Albania</asp:ListItem>
</asp:DropDownList>