this is my code ..while editing and deleting row index always taking zero on-wards...delete command not at all working....if i try to edit anything only 2nd row onwards its working...delete command not at all working..i think it is because of row index..please any one help me thanks in advance....
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Manager_Payments : System.Web.UI.Page
{
//SqlConnection con =new SqlConnection("Data Source=sqlexpress;Initial Catalog=isoqrmssys;User ID=sa;password=123456;Integrated Security=True");
Business BL = new Business();
//protected Int64 stf_ID, vmember;
//protected DateTime SRDT;
private System.Drawing.Color a;
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
protected void Page_Load(object sender, EventArgs e)
{
loadgridview();
}
private void loadgridview()
{
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("select * from CustomerProfMain", con);
//string sql = "SELECT * FROM CustomerProfMain";
SqlDataAdapter sda = new SqlDataAdapter(cmd);
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
//return ds.Tables[0];
Grd_View.DataSource = ds.Tables[0];
Grd_View.DataBind();
con.Close();
}
protected void Grd_View_RowCommand(Object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
int index = Grd_View.SelectedIndex;
if (e.CommandName == "Edit")
{
//string RowIndex = int.Parse(e.CommandArgument.ToString());
// Session["rowid"] = RowIndex;
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("Select * from CustomerProfMain where CustomerCode='" + e.CommandArgument.ToString() + "'", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
dt=ds.Tables[0];
TextBox1.Text = dt.Rows[0]["CustomerName"].ToString();
TextBox2.Text=dt.Rows[0]["Address"].ToString();
TextBox3.Text=dt.Rows[0]["TellNo"].ToString();
TextBox4.Text=dt.Rows[0]["FaxNo"].ToString();
TextBox5.Text=dt.Rows[0]["Email"].ToString();
Button1.Text = "Update";
}
if (e.CommandName == "Delete")
{
int RowIndex = int.Parse(e.CommandArgument.ToString());
Session["rowid"] = RowIndex;
// DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("Delete from CustomerProfMain where CustomerCode='" + RowIndex + "' ", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
protected void Grd_View_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void Grd_View_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void Grd_View_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Button1.Text == "Add")
{
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(myStr);
con.Open();
string sql = string.Empty;
sql = "insert into CustomerProfMain(CustomerName,Address,TellNo,FaxNo,Email) values('" + TextBox1.Text.Trim() + "','" + TextBox2.Text.Trim() + "','" + TextBox3.Text.Trim() + "','" + TextBox4.Text.Trim() + "','" + TextBox5.Text.Trim() + "') ";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
Button1.Text = "Add";
loadgridview();
}
if (Button1.Text == "Update")
{
string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(myStr);
con.Open();
string sql = string.Empty;
sql = "update CustomerProfMain set CustomerName='" + TextBox1.Text.Trim() + "',Address='" + TextBox2.Text.Trim() + "',TellNo='" + TextBox3.Text.Trim() + "',FaxNo='" + TextBox4.Text.Trim() + "',Email='" + TextBox5.Text.Trim() + "' where CustomerCode='" + Session["rowid"] + "'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
Button1.Text = "Add";
loadgridview();
}
}
}
"<asp:GridView ID="Grd_View" ShowFooter="True" runat="server" OnRowEditing="Grd_View_RowEditing" AutoGenerateColumns="False"
DataKeyNames="CustomerCode" cellpadding="4" OnRowCommand="Grd_View_RowCommand" GridLines="None"
AllowPaging="True" AllowSorting="True" CssClass="style2" ForeColor="#333333" Width="569px" OnRowDataBound="Grd_View_RowDataBound" OnRowDeleting="Grd_View_RowDeleting">
<FooterStyle BackColor="#555555" ForeColor="White" Font-Bold="True" />
<Columns>
<asp:BoundField DataField="CustomerCode" HeaderText="CustomerCode" InsertVisible="False"
ReadOnly="True" SortExpression="CustomerCode" />
<asp:BoundField DataField="CustomerName" HeaderText="CustomerName" SortExpression="CustomerName" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="TellNo" HeaderText="TellNo" SortExpression="TellNo" />
<asp:BoundField DataField="FaxNo" HeaderText="FaxNo" SortExpression="FaxNo" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:CommandField ShowEditButton="true" SelectText="Edit" />
<asp:CommandField ShowDeleteButton="true" SelectText="Delete" />
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#777777" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#555555" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
"
Replace your grid view with this code
<asp:GridView ID="Grd_View" ShowFooter="True" runat="server" OnRowEditing="Grd_View_RowEditing" AutoGenerateColumns="False"
DataKeyNames="CustomerCode" CellPadding="4" OnRowCommand="Grd_View_RowCommand" GridLines="None"
AllowPaging="True" AllowSorting="True" CssClass="style2" ForeColor="#333333" Width="569px" OnRowDataBound="Grd_View_RowDataBound" OnRowDeleting="Grd_View_RowDeleting">
<FooterStyle BackColor="#555555" ForeColor="White" Font-Bold="True" />
<Columns>
<asp:BoundField DataField="CustomerCode" HeaderText="CustomerCode" InsertVisible="False"
ReadOnly="True" SortExpression="CustomerCode" />
<asp:BoundField DataField="CustomerName" HeaderText="CustomerName" SortExpression="CustomerName" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="TellNo" HeaderText="TellNo" SortExpression="TellNo" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" CommandArgument='<%#Eval("CustomerCode")%>' CommandName="Edit" Text="Edit">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnDelete" runat="server" CommandArgument='<%#Eval("CustomerCode")%>' CommandName="Delete" Text="Delete">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#777777" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#555555" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
You didn't set CommandArgument here we set it as CommandArgument='<%#Eval("CustomerCode")%>' to your edit button and delete button
Try doing the following...on page load bind the grid ONLY if it's not a postback...
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
loadgridview();
}
Then re-bind the grid at the end of the command event handler, I'll remove some data access logic for clarity...
protected void Grd_View_RowCommand(Object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
int index = Grd_View.SelectedIndex;
if (e.CommandName == "Edit")
{
//...
loadgridview();
}
if (e.CommandName == "Delete")
{
//...
loadgridview();
}
}
Try this and Set GridView's AutoPostback property to true
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
loadgridview();
}
}
Related
Here is my case.
I've saved data from CheckBoxList:
foreach (ListItem li in CheckBoxList1.Items)
{
Steps = String.Join(", ", CheckBoxList1.Items.Cast<ListItem>()
.Where(i => i.Selected));
}
It works fine but what I want is to get back this data from database in checkBoxList inside a DataGrid.
And bellow are many things I tried. Please help:
<div align="center" style="margin-top: 50px;">
<asp:GridView ID="GridView1" runat="server" BackColor="White" DataKeyNames="SNo"
OnRowUpdating="GridView1_RowUpdating" AutoGenerateColumns="False"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing"
BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Vertical" ShowFooter="True" OnRowDataBound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="TransactionName" HeaderText="Transaction Name" />
<asp:BoundField DataField="Category" HeaderText="Category" />
<asp:TemplateField HeaderText="Steps">
<ItemTemplate>
<asp:Label ID="lblBrand" runat="server" Text='<%#Eval("Steps") %>'>
</asp:Label>
<asp:CheckBoxList ID="CheckBoxList2" runat="server">
</asp:CheckBoxList>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<EditRowStyle Height="10px" Width="2px" />
<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>
The C# code behind
private void Bind_CheckBoxList()
{
DataTable dt;
String SQL = "SELECT * from TransactionDetail";
string sConstr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr))
{
using (SqlCommand comm = new SqlCommand(SQL, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt = new DataTable("tbl");
da.Fill(dt);
}
conn.Close();
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBoxList c = (CheckBoxList)e.Row.FindControl("CheckBoxList2");
DataTable dt;
String SQL = "SELECT * FROM TransactionDetail";
string sConstr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr))
{
using (SqlCommand comm = new SqlCommand(SQL, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
if (c != null)
{
Label test = (Label)(e.Row.FindControl("lblBrand"));
Steps = test.Text;
string[] items = Steps.Split(new[] { ", " }, StringSplitOptions.None);
foreach (ListItem li in c.Items)
li.Selected = items.Contains(li.Text);
}
dt = new DataTable("tbl");
da.Fill(dt);
}
}
c.DataSource = dt;
c.DataTextField = what to write here to pass the array Text;
c.DataValueField = "SNo";
c.DataBind();
}
}
Hey thanks i solve it by creating another table for Steps and same for Documents Required ,,, its now showing the checkBoxList that i want into the datagrid and bellow the Code
if ((e.Row.RowState & DataControlRowState.Edit) == 0)
{
CheckBoxList c = (CheckBoxList)e.Row.FindControl("CheckBoxList2");
CheckBoxList CheckBoxListDR = (CheckBoxList)e.Row.FindControl("CheckBoxList3");
DataTable dt;
String SQL = "SELECT distinct S.Steps, D.DocumentsRequired, T.TransactionID FROM [StepsIsSelectedTable] S JOIN TransactionDetail T " +
" ON S.TransactionIDSteps = T.TransactionID JOIN DocumentsRequiredIsSelected D " +
"ON D.TransactionIDDR = T.TransactionID WHERE " +
"TransactionIDDR ='" + TreeView1.SelectedValue + "' and S.StepsIsSelected='True' and D.DocumentsRequiredIsSelected='True'" +
" group by S.Steps, D.DocumentsRequired ,T.TransactionID";
string sConstr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(sConstr))
{
using (SqlCommand comm = new SqlCommand(SQL, conn))
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(comm))
{
dt = new DataTable("tbl");
da.Fill(dt);
}
}
c.DataSource = dt;
CheckBoxListDR.DataSource = dt;
c.DataTextField = "Steps";
c.DataValueField = "TransactionID";
CheckBoxListDR.DataTextField = "DocumentsRequired";
CheckBoxListDR.DataValueField = "TransactionID";
c.DataBind();
c.SelectedValue = "TransactionID";
CheckBoxListDR.DataBind();
CheckBoxListDR.SelectedValue = "1";
}
}
I don't normally work with OnRowDataBound, but I need to in this case because I need to change the back color of rows based on a specific field.
Here's my ASPX:
<div id="divGrid" style='width:920px; height:430px; overflow:auto'>
<asp:DataGrid ID="DataGrid_AuditSearch" runat="server"
AllowPaging="True" AllowSorting="True" CellPadding="4" ForeColor="#333333"
GridLines="None" AutoGenerateColumns="False"
OnRowDataBound="DataGrid_AuditSearch_RowDataBound"
OnCancelCommand="DataGrid_AuditSearch_CancelCommand"
OnUpdateCommand="DataGrid_AuditSearch_UpdateCommand"
OnEditCommand="DataGrid_AuditSearch_EditCommand">
<AlternatingItemStyle Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<EditItemStyle BackColor="#999999" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<PagerStyle BackColor="#5D7B9D" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Width="920px" Font-Underline="False" />
<SelectedItemStyle BackColor="#E2DED6" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<Columns>
<asp:EditCommandColumn ButtonType="PushButton" CancelText="Cancel"
EditText="Select" UpdateText="Update"></asp:EditCommandColumn>
<asp:BoundColumn DataField="AUDIT_ID" HeaderText="Audit ID"/>
<asp:BoundColumn DataField="PLAN_ID" HeaderText="Plan ID"/>
<asp:BoundColumn DataField="PLAN_DESC" HeaderText="Plan Desc"/>
<asp:BoundColumn DataField="DOC_TYPE" HeaderText="Doc Type"/>
<asp:BoundColumn DataField="PRODUCT" HeaderText="Product"/>
<asp:BoundColumn DataField="PLAN_TYPE" HeaderText="Plan Type"/>
<asp:BoundColumn DataField="Auditor_ID" HeaderText="Auditor ID"/>
</Columns>
</asp:DataGrid>
<asp:Label ID="lblEmpty" runat="server" Visible="false" Style="font-weight:bold; font-size:large;"></asp:Label>
</div>
and here's my C# Code-Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Sometimes you need the parameter, sometimes you don't. This works for both cases.
txtAuditSearch.Text = (Request["AuditID"] ?? String.Empty).ToString();
Show_Data(0);
}
else
{
}
}
public void Show_Data(int AuditID)
{
OracleConnection conn = GetConnection();
try
{
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnCST"].ToString();
OracleCommand cmd3 = new OracleCommand();
cmd3.Connection = conn;
string sqlquery2;
//sqlquery2 = "SELECT * FROM F_Audit_Plan Where Audit_ID = " + AuditID + "";
sqlquery2 = "SELECT FAP.AUDIT_ID, FAP.PLAN_ID, FAP.PLAN_DESC, DTY.DOC_TY AS DOC_TYPE, DP.PRODUCT, ";
sqlquery2 = sqlquery2 + "DPT.PLAN_TYPE, FA.Auditor_Lan_ID AS Auditor_ID, FAP.Plan_Review_Ind ";
sqlquery2 = sqlquery2 + "FROM F_Audit_Plan FAP ";
sqlquery2 = sqlquery2 + "LEFT JOIN D_DOC_TY DTY ";
sqlquery2 = sqlquery2 + "ON FAP.DOC_TY_ID = DTY.DOC_TY_ID ";
sqlquery2 = sqlquery2 + "LEFT JOIN D_PRODUCT DP ";
sqlquery2 = sqlquery2 + "ON FAP.PRODUCT_ID = DP.PRODUCT_ID ";
sqlquery2 = sqlquery2 + "LEFT JOIN D_PLAN_TYPE DPT ";
sqlquery2 = sqlquery2 + "ON FAP.PLAN_TY_ID = DPT.PLAN_TY_ID ";
sqlquery2 = sqlquery2 + "LEFT JOIN F_Audit FA ";
sqlquery2 = sqlquery2 + "ON FA.Audit_ID = FAP.Audit_ID ";
sqlquery2 = sqlquery2 + "Where FAP.Audit_ID = " + AuditID + " ";
sqlquery2 = sqlquery2 + "ORDER BY FAP.PLAN_DESC ASC ";
cmd3.CommandText = sqlquery2;
var SearchAdapter = new OracleDataAdapter(cmd3);
var ds = new DataSet();
SearchAdapter.Fill(ds);
// Perform the binding.
DataGrid_AuditSearch.DataSource = ds;
DataGrid_AuditSearch.DataBind();
if (DataGrid_AuditSearch.Items.Count < 1)
{
lblEmpty.Visible = true;
lblEmpty.Text = "There is no data to display";
}
else
{
lblEmpty.Visible = false;
}
conn.Close();
//DataGrid_AuditSearch.Columns[3].Visible = false;
//DataGrid_AuditSearch.Columns[1].Visible = false;
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
conn.Close();
}
}
protected void DataGrid_AuditSearch_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string Status = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Plan_Review_Ind"));
if (Status == "Y")
{
e.Row.Attributes["style"] = "background-color: #28b779";
}
else
{
e.Row.Attributes["style"] = "background-color: #da5554";
}
}
}
I put a break point on the first line in the DataGrid_AuditSearch_RowDataBound function and it never even hits it. Any idea what I'm doing wrong?
Check this guy out, looks like setting AutoGenerateColumns="False" breaks this some.
You are using a DataGrid, not a GridView. The DataGrid does not have an OnRowDataBound event. Use the OnItemDataBound event instead.
Read more about it at Microsoft.
Here is my aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1"
OnRowCommand="GridView1_RowCommand" AutoGenerateSelectButton="True" EnablePersistedSelection="True">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Class" HeaderText="Class" SortExpression="Class" />
<asp:BoundField DataField="Section" HeaderText="Section"
SortExpression="Section" />
<asp:BoundField DataField="Address" HeaderText="Address"
SortExpression="Address" />
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button runat="server" ID="btnedit" Text="Edit" CommandName="EditRow"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Button runat="server" ID="btndelete" Text="Delete" CommandArgument='<%# Container.DataItemIndex %>' CommandName="Deleterow"></asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is code behind:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
GridViewRow gr = GridView1.SelectedRow;
gr.Cells[1].Text = Textusername.Text;
gr.Cells[2].Text = Textclass.Text;
gr.Cells[3].Text = Textsection.Text;
gr.Cells[4].Text = Textaddress.Text;
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
}
The selected row did not select in gridview. May i know how to enable gridview row. I used msdn and other documents and i followed,but nothing helps.
I design i set enable selection, but still i didn't find out issue.
Can anyone help me?
Thanks,
Basically we get SelectedRow of GridView Upon some GridviewRow Action event like OnSelectedIndexChanged , OnSelectedIndexChanging , OnRowEditing or from Template control like Button click. But here in your coding I don't think your btnsub_Click is inside Gridview so If you want to use the SelectedGridViewRow after your GridviewRow Action event then save the index in some temporary variable or pass the variable to method as argument.
protected void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
{
int index = Gridview1.SelectedIndex;
hiddenfield.Value = index.ToString();
}
OR In OnRowEditing also you can get the index of row
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditRow")
{
GridViewRow gr = (GridViewRow)((Button)e.CommandSource).NamingContainer;
int index = gr.RowIndex;
hidval.Value = index.ToString();
}
}
and on button Click you can get the hiddenfield value as index:
protected void btnsub_Click(object sender, EventArgs e)
{
SqlConnection con = Connection.DBconnection();
if (Textid.Text.Trim().Length > 0)
{
SqlCommand com = new SqlCommand("StoredProcedure3", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#id", Textid.Text.Trim());
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
if(!String.IsNullOrEmpty(hiddenfield.Value))
{
int index = Convert.ToInt16(hiddenfield.Value);
GridView1.Rows[index].Cells[1].Text = Textusername.Text;
GridView1.Rows[index].Cells[2].Text = Textclass.Text;
GridView1.Rows[index].Cells[3].Text = Textsection.Text;
GridView1.Rows[index].Cells[4].Text = Textaddress.Text;
}
}
else
{
SqlCommand com = new SqlCommand("StoredProcedure1", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", Textusername.Text.Trim());
com.Parameters.AddWithValue("#Class", Textclass.Text.Trim());
com.Parameters.AddWithValue("#Section", Textsection.Text.Trim());
com.Parameters.AddWithValue("#address", Textaddress.Text.Trim());
com.ExecuteNonQuery();
Response.Redirect("studententry.aspx");
}
}
I am having a little trouble with paging in a nested grid view.
When I try to change page I am getting some very strange and unexpected behaviour. Sometimes it will post back but not actually change the page and sometimes it does change the page but not as expected, it is messing with the order so you will have some items from the previous page still.
My markup is as follows:
<asp:GridView
ID="grdImages"
runat="server"
AllowPaging="true"
ShowFooter="true"
PageSize="5"
AutoGenerateColumns="false"
OnPageIndexChanging="grdImages_PageIndexChanging"
OnRowCancelingEdit="grdImages_RowCancelingEdit"
OnRowCommand="grdImages_RowCommand"
OnRowEditing="grdImages_RowEditing"
OnRowUpdating="grdImages_RowUpdating"
OnRowDeleting="grdImages_RowDeleting"
EmptyDataText="No Data Available at this Time"
OnRowDataBound="grdImages_RowDataBound"
DataKeyNames="ProductId">
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField AccessibleHeaderText="Product ID" HeaderText="Product ID" FooterText="Product ID">
<ItemTemplate>
<asp:Label ID="lblProdId" runat="server" Text='<%# Eval("ProductId") %>' ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="lstAddProdId" runat="server" AppendDataBoundItems="true" >
<asp:ListItem>Select a product</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Product Main Image" FooterText="Product Main Image" HeaderText="Product Main Image">
<ItemTemplate>
<asp:Label ID="lblMainImgId" runat="server" Text='<%# Eval("ImageId") %>' ></asp:Label>
<asp:Label ID="lblMainImgName" runat="server" Text='<%# Eval("ImageName") %>' ></asp:Label> <br />
<asp:Image ID="imgMain" runat="server" Height="250" Width="250" ImageUrl='<%# Eval("ImagePath") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="flupEditMain" runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupMain" runat="server" AllowMultiple="false" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Supporting Images" FooterText="Supporting Images" HeaderText="Supporting Images">
<ItemTemplate>
<asp:GridView ID="grdSupImages"
runat="server" ShowHeader="false" CellPadding="4"
ForeColor="#333333" GridLines="None" AutoGenerateColumns="False"
OnRowEditing="grdSupImages_RowEditing"
OnRowUpdating="grdSupImages_RowUpdating" AllowPaging="true" PageSize="4"
OnPageIndexChanging="grdSupImages_PageIndexChanging" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775"></AlternatingRowStyle>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="imgSupId" runat="server" Text='<%# Eval("ImgId") %>' ></asp:Label>
<asp:Image ID="imgSup" runat="server" AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
<asp:Label ID="imgSupName" runat="server" Text='<%# Eval("ImageName") %>' AssociatedControlID="imgSup"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Image ID="imgSup" runat="server" AlternateText='<%# Eval("ImageName") %>' ImageUrl='<%# Eval("ImagePath") %>' Height="125" Width="125" />
<asp:CheckBox ID="chkSupImages" runat="server" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
</ItemTemplate>
<FooterTemplate>
<asp:FileUpload ID="flupExtra" runat="server" AllowMultiple="true" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<br />
<span onclick="return confirm('Are you sure you want to delete these images?')">
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<br />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAddRecord" runat="server" Text="Add" CommandName="Add"></asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999"></EditRowStyle>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White"></HeaderStyle>
<PagerStyle HorizontalAlign="Center" BackColor="#284775" ForeColor="White"></PagerStyle>
<RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#E9E7E2"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#506C8C"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#FFFDF8"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#6F8DAE"></SortedDescendingHeaderStyle>
</asp:GridView>
My code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.IO;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class Admin_ProductManagement_addProdImage : System.Web.UI.Page
{
private string connectionString =
WebConfigurationManager.ConnectionStrings["bncConn"].ConnectionString;
private string imageDirectory;
protected void Page_Load(object sender, EventArgs e)
{
// ensure images are uploaded to the right folder.
imageDirectory = Path.Combine(
Request.PhysicalApplicationPath, #"Images\ProductImages");
if (!this.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
// define ado.net objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "DisplayMain";
try
{
con.Open(); // try to open the connection
DataSet ds = new DataSet(); // Initializes a new instance of the DataSet class
adapter.Fill(ds, "ProductImages"); // Adds or refreshes rows in the DataSet to match those in the data source using the DataSet and DataTable names
grdImages.DataSource = ds; // sets the gridview datasource
grdImages.DataBind(); // binds data to gridview
// find dropdownlist in the footer row of the gridview
DropDownList prods = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId");
// call function
lstProducts(prods);
}
catch (Exception err)
{
lblGrdImages.Text = "BindGrid error: " + err.Message + err.Source + err.StackTrace; // display exceptions in label
}
finally
{
con.Close(); // close connection, even if action was unsuccessful.
}
}
protected void BindNestedGrid(int product, GridView grd)
{
// define ado.net objects.
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "DisplayExtra";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = product;
// try to connect, fill dataset and close connection. Also catch exceptions.
try
{
con.Open(); // open the connection.
DataSet rds = new DataSet(); // initialize a data set.
adapt.Fill(rds, "ExtraImages"); // fills dataset
grd.DataSource = rds; // assign data source.
grd.DataBind(); // bind data.
}
catch (Exception err)
{
lblGrdImages.Text = "Bind Nested Grid Error: " + err.Message; // catch exceptions.
}
finally
{
con.Close(); // close the db connection
}
}
protected void lstProducts(DropDownList prods)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader;
// define the sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "LstProds";
try
{
con.Open(); // try to connect to db.
reader = cmd.ExecuteReader(); // execut the reader
while (reader.Read())
{
ListItem item = new ListItem(); // create listitem
item.Text = reader["ProductName"].ToString(); // add product name to item text
item.Value = reader["ProductId"].ToString(); // add productId to item value
prods.Items.Add(item); // populate dropdown list.
}
}
catch (Exception err)
{
lblGrdImages.Text = "List Products Error: " + err.Message; // display error message in a label
}
finally
{
con.Close(); // close the connection.
}
}
protected void addMain(int ProdId, string ImgName, string ImgPath)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "AddMain";
cmd.Parameters.Add(new SqlParameter("#ImageName", SqlDbType.VarChar, 50));
cmd.Parameters["#ImageName"].Value = ImgName;
cmd.Parameters.Add(new SqlParameter("#ImagePath", SqlDbType.VarChar, -1));
cmd.Parameters["#ImagePath"].Value = ImgPath;
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = ProdId;
try
{
con.Open(); // attempt to open the connection
DataSet ds = new DataSet(); // initialize the dataset
adapter.Fill(ds, "ProductImages"); // fill the data set.
}
catch (Exception err)
{
lblGrdImages.Text = "Add main error: " + err.Message; // display exceptions in a label control
}
finally
{
con.Close(); // close connection.
}
}
protected void addExtraImages(int ProductId, string ExImgName, string ExImagePath)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "AddExtra";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = ProductId;
cmd.Parameters.Add(new SqlParameter("#ImageName", SqlDbType.VarChar,50));
cmd.Parameters["#ImageName"].Value = ExImgName;
cmd.Parameters.Add(new SqlParameter("#ImagePath", SqlDbType.VarChar,-1));
cmd.Parameters["#ImagePath"].Value = ExImagePath;
try
{
con.Open(); // try to open db connection
DataSet ds = new DataSet(); // initialize data set.
adapter.Fill(ds, "ProductImages"); // fill the data set.
}
catch (Exception err)
{
lblGrdImages.Text = "Add extra images error: " + err.Message; // display exception in a label
}
finally
{
con.Close(); // close the connection
}
}
protected void DeleteProductImages(int Product)
{
// define ado.net objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("ProductDetails.bnc_ProductImages", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// define sp parameters
cmd.Parameters.Add(new SqlParameter("#Status", SqlDbType.VarChar, 50));
cmd.Parameters["#Status"].Value = "Delete";
cmd.Parameters.Add(new SqlParameter("#ProductId", SqlDbType.Int));
cmd.Parameters["#ProductId"].Value = Product;
try
{
con.Open(); // open connection
DataSet ds = new DataSet(); // initialize rthe dataset
adapter.Fill(ds); // fill dataset.
}
catch (Exception err)
{
lblGrdImages.Text = "Delete error: " + err.Message; // report error in a label.
}
finally
{
con.Close(); // close the connection.
}
}
protected void grdImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdImages.PageIndex = e.NewPageIndex; // sets the page index
BindGrid(); // bind the grid.
}
protected void grdImages_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdImages.EditIndex = -1; // sets the page index
BindGrid(); // bind the grid.
}
private bool isValid(HttpPostedFile file, string[] extAry, string ext) // checks extension
{
bool isValid = false;
for (int i = 0; i < extAry.Length; i++)
{
if (ext.ToLowerInvariant().IndexOf(extAry[i]) > -1)
isValid = true;
}
return isValid;
}
protected void uploadMainImage() {
string[] validFileTypes = { ".jpg", ".png" }; // file type array
FileUpload main = (FileUpload)grdImages.FooterRow.FindControl("flupMain"); // find control
DropDownList products = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId"); // find control
string mainFile = Path.GetFileName(main.PostedFile.FileName); // get file name.
string ext = Path.GetExtension(mainFile); // get file extension.
if (isValid(main.PostedFile, validFileTypes, ext)) // check if file extension is valid.
{
if (File.Exists(mainFile)) // check if file exists
{
lblGrdImages.Text = "File with the name: " + mainFile + " already exists. Please rename or choose a different file.";
}
else
{
try
{
string serverFileName = Path.GetFileName(mainFile); // assign values to variables
string uploadPath = Path.Combine(imageDirectory, serverFileName);
int Product = Convert.ToInt32(products.SelectedValue);
main.SaveAs(uploadPath); // save file
addMain(Product, serverFileName, #"~\Images\ProductImages\" + serverFileName); // Call stored procedure
}
catch (Exception err)
{
lblGrdImages.Text = err.Message;
}
}
}
}
protected void uploadExtraImages()
{
string[] validFileTypes = { ".jpg", ".png" }; // file type array
FileUpload extra = (FileUpload)grdImages.FooterRow.FindControl("flupExtra"); // find conrol
DropDownList products = (DropDownList)grdImages.FooterRow.FindControl("lstAddProdId"); // find control
if (extra.HasFiles)
{
foreach (HttpPostedFile file in extra.PostedFiles)
{
string ext = Path.GetExtension(file.FileName);
if (isValid(file, validFileTypes, ext)) // check file extension
{
string serverFileName = Path.GetFileName(file.FileName); // assign values to variables
string uploadPath = Path.Combine(imageDirectory, serverFileName);
int Product = Convert.ToInt32(products.SelectedValue);
try
{
file.SaveAs(uploadPath); // save file
addExtraImages(Product, serverFileName, #"~\Images\ProductImages\" + serverFileName); // call stored procedure
}
catch (Exception err)
{
lblGrdImages.Text = "Error: " + err.Message;
}
}
}
}
}
protected void grdImages_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Add"))
{
// find the required controls in the grdview.
FileUpload main = (FileUpload)grdImages.FooterRow.FindControl("flupMain");
FileUpload extra = (FileUpload)grdImages.FooterRow.FindControl("flupExtra");
if (main.HasFile)
{
uploadMainImage();
if (extra.HasFiles)
{
uploadExtraImages();
}
grdImages.EditIndex = -1;
BindGrid();
}
else
{
lblGrdImages.Text = "Product main image is required.";
}
}
}
protected void grdImages_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (!this.IsPostBack)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView grd = (GridView)e.Row.FindControl("grdSupImages"); // find controls
Label prodId = (Label)e.Row.FindControl("lblProdId");
int product = Convert.ToInt32(prodId.Text); // assign values to variables.
BindNestedGrid(product, grd); // call the function.
}
}
}
protected void grdImages_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// find controls
Label product = (Label)grdImages.Rows[e.RowIndex].FindControl("lblProdId");
Label image = (Label)grdImages.Rows[e.RowIndex].FindControl("lblMainImgName");
GridView grd = (GridView)grdImages.Rows[e.RowIndex].FindControl("grdSupImages");
// declare variables and assign values
int prodid = Convert.ToInt32(product.Text);
string path = Server.MapPath(#"~\Images\ProductImages\" + image.Text);
File.Delete(path);
foreach(GridViewRow row in grd.Rows)
{
Label img = (Label)row.FindControl("imgSupName");
string imgName = img.Text;
string imgPath = Server.MapPath(#"~\Images\ProductImages\" + imgName);
try
{
File.Delete(imgPath);
}
catch (Exception err)
{
lblGrdImages.Text = "File Delete Error: " + err.Message + "<br />" + err.InnerException + "||" + err.StackTrace;
}
}
DeleteProductImages(prodid);
grdImages.EditIndex = -1;
BindGrid();
}
protected void grdImages_RowEditing(object sender, GridViewEditEventArgs e)
{
grdImages.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void grdImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void grdSupImages_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void grdSupImages_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
}
}
I would be eternally grateful of any assistance with this matter. If you require any further information please let me know and I will provide.
Although nobody wanted to help me, I have found the answer to my problem.
I thought id share this information as it may be able to help somebody else.
This is what I came up with for my child gridview pageindexchanging event:
protected void grdSupImages_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gv = (GridView)sender;
gv.PageIndex = e.NewPageIndex;
BindNestedGrid(Convert.ToInt32(gv.ToolTip), gv);
}
I have a C# .Net application with a gridview within an Ajax Modal Popup (VS2008). I have the grid view set to return 10 records per page with paging enabled.
When the user clicks to change page within the gridview there is a postback which closes the modal window and then opens it again using ModalPopup.show();
Is there any way to avoid the postback of the whole page and just postback the gridview whilst keeping the modal window active? At the moment the postback of the whole page gives the impression of flicker...
<asp:Panel ID="Panel1" runat="server" Font-Italic="True"
Font-Names="Times New Roman" Font-Size="Small" ForeColor="#82B8DE">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None"
onpageindexchanging="GridView1_PageIndexChanging"
onrowdatabound="GridView1_RowDataBound"
onselectedindexchanged="GridView1_SelectedIndexChanged"
SelectedIndex="0" ShowHeader="False" Width="700px" ControlID="GridView1"
EventName="PageIndexChanging" Font-Italic="True" Font-Names="Times New Roman"
Font-Size="Medium">
<PagerSettings PageButtonCount="12" />
<RowStyle CssClass="RowStyle" BackColor="#EFF3FB" Font-Italic="True"
Font-Names="Times New Roman" Font-Size="Small" ForeColor="#82B8DE" />
<Columns>
<asp:BoundField DataField="Address" ReadOnly="True">
<ItemStyle Width="385px" />
</asp:BoundField>
<asp:BoundField DataField="XCoord" ReadOnly="True" ShowHeader="False" >
<ItemStyle CssClass="Hidden" />
</asp:BoundField>
<asp:BoundField DataField="YCoord" ReadOnly="True" ShowHeader="False" >
<ItemStyle CssClass="Hidden" />
</asp:BoundField>
</Columns>
<FooterStyle CssClass="FooterStyle" BackColor="#507CD1" Font-Bold="True"
ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle CssClass="SelectedRowStyle" BackColor="#D1DDF1"
Font-Bold="True" ForeColor="#333333" />
<HeaderStyle CssClass="HeaderStyle" BackColor="#507CD1" Font-Bold="True"
ForeColor="White" />
<EditRowStyle BackColor="#2461BF" Font-Italic="True"
Font-Names="Times New Roman" Font-Size="Medium" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</asp:Panel>
<ajax:ModalPopupExtender ID="ModalPopupExtender1" runat="server" PopupControlID="Panel1" TargetControlID="dummy"
BackgroundCssClass="ModalBackgroundGrid" BehaviorID="ModalGrid">
</ajax:ModalPopupExtender>
And the code behind...
public void Page_Load(object sender, EventArgs e)
{
try
{
if (!(Page.IsPostBack))
{
GridView1.EnableViewState = true;
GridView1.AllowPaging = true;
GridView1.PageSize = 10;
GridView1.PagerSettings.Mode = PagerButtons.Numeric;
GridView1.Visible = true;
}
if (!m_bDisclaimerShown)
{
m_bDisclaimerShown = true;
mpe1.Show();
TabContainer.Visible = true;
ScaleBar1.Visible = true;
}
}
catch (Exception ex)
{
ShowMsg("Error - " + ex.Message);
}
}
protected void btnHide_Click(object sender, EventArgs e)
{
mpe1.Hide();
TabContainer.Visible = true;
ScaleBar1.Visible = true;
}
protected void cmdZoomAddress_Click(object sender, EventArgs e)
{
try
{
if (txtPostCode.Text.Length >= 7 && OpenDB())
{
string strPostcode = txtPostCode.Text;
strPostcode = strPostcode.Substring(0, 4) + strPostcode.Substring(strPostcode.Length - 3, 3);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = m_sqlConn;
sqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
sqlCmd.CommandText = "sde.dbo.sp_selAddressByPostcode";
sqlCmd.Parameters.Add("#Postcode", SqlDbType.VarChar);
sqlCmd.Parameters["#Postcode"].Value = strPostcode;
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCmd);
m_sqlDataTable = new DataTable();
sqlAdapter.Fill(m_sqlDataTable);
GridView1.DataSource = m_sqlDataTable;
GridView1.DataBind();
GridView1.Visible = true;
ModalPopupExtender1.Show();
}
else
{
ShowMsg("Error - No Postal Addresses Returned");
}
}
catch (Exception ex)
{
ShowMsg("Error - " + ex.Message);
}
finally
{
CloseDB();
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
if (sender != null)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = m_sqlDataTable;
GridView1.DataBind();
ModalPopupExtender1.Show();
}
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow GVRow = GridView1.SelectedRow;
int iX = (int)Convert.ToSingle(GVRow.Cells[1].Text);
int iY = (int)Convert.ToSingle(GVRow.Cells[2].Text);
GridView1.Visible = false;
MoveMap(iX, iY);
}
public void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItemIndex >= 0)
{
e.Row.Attributes["style"] = "cursor:pointer";
e.Row.Attributes.Add("onMouseOver", "this.style.cursor='hand';");
e.Row.Attributes.Add("onclick", ClientScript.GetPostBackEventReference(GridView1, "Select$" + e.Row.RowIndex.ToString()));
}
}
protected override void Render(HtmlTextWriter writer)
{
foreach (GridViewRow r in GridView1.Rows)
{
if (r.RowType == DataControlRowType.DataRow)
{
Page.ClientScript.RegisterForEventValidation(GridView1.UniqueID, "Select$" + r.RowIndex);
}
}
base.Render(writer);
}
thanks for your suggestion. I've put the gridview into a...
<asp:UpdatePanel>
<ContentTemplate>
The modal now stays however when I click a record in the grid view it doesn't close!