Related
I'm trying to get an Automatic ID filler for a gridview footer text box, but every time I run I get the "Not Referred Instance of an object" meaning the method isn't finding the Text box, Right?
But I have the same text box in other method and is working correctly, what its wrong?
Below is the code sample of GridView
<asp:GridView ID="GridView1" runat="server" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" AutoGenerateColumns="False" ShowFooter="True">
<Columns>
<asp:TemplateField HeaderText="ID UNIDAD">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddID" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%# Bind("ID_UNIDAD") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UNIDAD">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNombre" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Nombre" runat="server" Text='<%# Bind("NOMBRE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FRACCIONES">
<EditItemTemplate>
<asp:CheckBox ID="TextBox3" runat="server" Checked='<%# Bind("FRACCIONES") %>'></asp:CheckBox>
</EditItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkFraccion" runat="server" ></asp:CheckBox>
</FooterTemplate>
<ItemTemplate>
<asp:CheckBox ID="lbl_Fraccion" runat="server" Checked='<%# Bind("FRACCIONES") %>' ></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CLAVE SAT">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtClave" runat="server" ></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lbl_Clave" runat="server" Text='<%# Bind("CLAVE_SAT") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<FooterTemplate>
<asp:ImageButton ID="Agregar" runat="server" ImageUrl="~/assets/iconos/add.ico" OnClick="Agregar_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
</asp:GridView>
Below is the code sample for binding the grid in 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.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Windows.Input;
public partial class Default2 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Integral Database"].ToString());
string query;
string countid = " ";
SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["Integral Database"].ToString());
string connStrr = ConfigurationManager.ConnectionStrings["Integral Database"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
llenagrid();
IncrementoID();
}
public void llenagrid()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(connStrr))
{
string sql = "SELECT id_unidad, nombre, fracciones, clave_sat from unidades";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
IncrementoID();
GridView1.DataSource = table;
GridView1.DataBind();
}
protected void Agregar_Click(object sender, ImageClickEventArgs e)
{
connStr.Open();
GridViewRow row = GridView1.FooterRow;
TextBox txtNombre = (TextBox)row.FindControl("txtNombre");
string str = "select count(nombre) from unidades where nombre like '"+txtNombre.Text+ "'";
SqlCommand com = new SqlCommand(str,connStr);
int count = Convert.ToInt32(com.ExecuteScalar());
connStr.Close();
if (count > 0)
{
string script = "alert('Este Nombre ya Existe.','AtenciĆ³n');";
ScriptManager.RegisterStartupScript(this, this.GetType(), "testScript", script, true);
}
else
{
connStr.Open();
TextBox txtID = (TextBox)row.FindControl("txtAddID");
CheckBox chkFracc = (CheckBox)row.FindControl("chkFraccion");
TextBox txtClave = (TextBox)row.FindControl("txtClave");
string ID = txtID.Text;
string Nombre = txtNombre.Text;
bool Fracc = chkFracc.Checked;
string clave = txtClave.Text;
string query2 = "Insert into unidades values('" + ID + "','" + Nombre + "','" + Fracc + "','" + clave + "')";
SqlCommand cmd2 = new SqlCommand(query2, connStr);
cmd2.ExecuteNonQuery();
connStr.Close();
llenagrid();
IncrementoID();
}
}
public void IncrementoID()
{
//query = "select Count(id_unidad) from unidades";
//con.Open();
//SqlCommand cmd = new SqlCommand(query, con);
//string cid = cmd.ExecuteScalar().ToString();
//con.Close();
//TextBox ID = (TextBox)GridView1.FooterRow.FindControl("txtAddID");
//ID.Text = countid + (int.Parse(cid) + 1);
//ID.ReadOnly = true;
con.Open();
SqlCommand cmd = new SqlCommand("select MAX (CAST( ID_UNIDAD as INT)) from unidades",con);
SqlDataReader rd = cmd.ExecuteReader();
TextBox txtID = ((TextBox)GridView1.FooterRow.FindControl("txtAddID"));
if (rd.Read())
{
string Value = rd[0].ToString();
if (Value == "")
{
txtID.Text = "1";
}
else
{
txtID.Text = rd[0].ToString();
txtID.Text = (Convert.ToInt64(txtID.Text) + 1).ToString();
}
}
con.Close();
}
}
As you can see, in the insert method it finds the gridview textbox (txtAddID) and when I try to use the same exact syntax in the IncrementoID Method it doesn't work.
Here is the problem in the method llenagrid(), before binding GridView you are trying to access the control that are in Gridview (inside method IncrementoID), So it's giving error as Not Referred Instance of an object means the Object you are trying to access is not yet referenced. Below code sample can help you out:
public void llenagrid()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(connStrr))
{
string sql = "SELECT id_unidad, nombre, fracciones, clave_sat from unidades";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
//IncrementoID(); // Remove the function call from here
GridView1.DataSource = table;
GridView1.DataBind();
IncrementoID(); // Call the function after GridView got binded.
}
Finally i was able to create a custom delete and edit button for my gridview. But I have noticed two problems in my gridview. Lets say i have a gridview shown below:
Problem 1:
When I click the delete button for the first time, it just refresh the page and does nothing. But when i click it for the second time, it executes perfectly. Why the delete button is not working and just refreshing page when clicked for the first time and then works at the second time?
Problem 2:
When I click the edit button for the first time, it works fine. Then, i can update/change the database. Lets say i want to change the name "Dean" under id "7" to "Jackson". So I just simply changed it in the textbox and clicked the update button. But the website just refresh again and the name "Dean" is still in the textbox(by the way, this is still in update/cancel mode). So I need to type "Jackson" again in the textbox and click the update button for the second time. This time it works and it did update my gridview. Similar to problem 1, why the update button is not working and just refreshing page when clicked for the first time and works at the second time?
Here is the aspx code:
<h3>Guitar Brands Data:</h3>
<div style="overflow:auto; width:1100px; max-height:500px;">
<asp:GridView ID="GuitarBrandsGridView" runat="server" CssClass="mydatagrid" PagerStyle-CssClass="pager" HeaderStyle-CssClass="header" RowStyle-CssClass="rows" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource0" OnRowDataBound="GuitarBrandsGridView_RowDataBound" OnRowCancelingEdit="GuitarBrandsGridView_RowCancelingEdit" OnRowEditing="GuitarBrandsGridView_RowEditing" OnRowUpdating="GuitarBrandsGridView_RowUpdating" OnRowDeleting="GuitarBrandsGridView_RowDeleting" Width="864px" Height="250px">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="GuitarBrandsGridViewBtnDelete" runat="server" CommandName="Delete" Text="Delete"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="GuitarBrandsGridViewBtnEdit" runat="server" CommandName="Edit" Text="Edit"/>
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="GuitarBrandsGridViewBtnUpdate" runat="server" CommandName="Update" Text="Update"/>
<asp:Button ID="GuitarBrandsGridViewBtnCancel" runat="server" CommandName="Cancel" Text="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="id" SortExpression="id">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="type" SortExpression="type">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("type") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("type") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="name" SortExpression="name">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="image" SortExpression="image">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("image") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("image") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="header"></HeaderStyle>
<PagerStyle CssClass="pager"></PagerStyle>
<RowStyle CssClass="rows"></RowStyle>
</asp:GridView>
</div>
<asp:SqlDataSource ID="SqlDataSource0" runat="server" ConnectionString="<%$ ConnectionStrings:brandsConnection %>" DeleteCommand="DELETE FROM [guitarBrands] WHERE [id] = #id" InsertCommand="INSERT INTO [guitarBrands] ([id], [type], [name], [image]) VALUES (#id, #type, #name, #image)" SelectCommand="SELECT [id], [type], [name], [image] FROM [guitarBrands]" UpdateCommand="UPDATE [guitarBrands] SET [type] = #type, [name] = #name, [image] = #image WHERE [id] = #id">
<DeleteParameters>
<asp:Parameter Name="id" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="id" Type="Int32" />
<asp:Parameter Name="type" Type="String" />
<asp:Parameter Name="name" Type="String" />
<asp:Parameter Name="image" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="type" Type="String" />
<asp:Parameter Name="name" Type="String" />
<asp:Parameter Name="image" Type="String" />
<asp:Parameter Name="id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<br/>
Here is the aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
BindGridViewDataList.GetItemsLoad();
}
//Start of Gridview Code for Guitar Brands
private void bindgridviewguitarbrands()
{
con1.Open();
cmd1.CommandText = "SELECT * FROM [guitarBrands]";
cmd1.Connection = con1;
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(ds1);
con1.Close();
GuitarBrandsGridView.DataBind();
}
protected void GuitarBrandsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string name = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "Name"));
Button button = (Button)e.Row.FindControl("GuitarBrandsGridViewBtnDelete");
button.Attributes.Add("onclick", "JavaScript:return ConfirmationBox('" + name + "' )");
}
}
protected void GuitarBrandsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString());
Label name = (Label)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("Label4");
con1.Open();
cmd1.CommandText = "DELETE FROM [guitarBrands] WHERE id=" + id;
cmd1.Connection = con1;
int a = cmd1.ExecuteNonQuery();
con1.Close();
if (a > 0)
{
bindgridviewguitarbrands();
}
RemoveCodeToGuitarFile.RemoveAddGuitarClass(name.Text);
RemoveCodeToGuitarFile.RemoveConnectionClassGuitarItems(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataASPX(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataCode(name.Text);
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx");
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx.cs");
ConnectionClassGuitarBrands.RemoveGuitarBrandsDatabase(name.Text);
}
protected void GuitarBrandsGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
string id = GuitarBrandsGridView.DataKeys[e.NewEditIndex].Value.ToString();
Label name = (Label)GuitarBrandsGridView.Rows[e.NewEditIndex].FindControl("Label4");
RemoveCodeToGuitarFile.RemoveAddGuitarClass(name.Text);
RemoveCodeToGuitarFile.RemoveConnectionClassGuitarItems(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataASPX(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataCode(name.Text);
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx");
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx.cs");
ConnectionClassGuitarBrands.RemoveGuitarBrandsDatabase(name.Text);
GuitarBrandsGridView.EditIndex = e.NewEditIndex;
bindgridviewguitarbrands();
}
// row update event
protected void GuitarBrandsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string id = GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString();
TextBox type = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("TextBox1");
TextBox name = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("TextBox2");
TextBox image = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("TextBox3");
cmd1 = new SqlCommand("UPDATE [guitarBrands] SET Type = '" + type + "', Name = '" + name + "', Image = '" + image + "' WHERE ID = " + id, con1);
con1.Open();
cmd1.ExecuteNonQuery();
con1.Close();
int ID = Convert.ToInt32(id);
ConnectionClassGuitarBrands.CreateGuitarBrandsDatabase(name.Text);
AddCodeToGuitarFile.AddGuitarClassCode(name.Text, ID);
AddCodeToGuitarFile.AddConnectionClassGuitarItems(name.Text);
AddCodeToGuitarFile.AddOverviewGuitarDataASPX(name.Text, ID);
AddCodeToGuitarFile.AddOverviewGuitarDataASPXCode(name.Text);
AddASPXAndCSFileForGuitarBrands.AddFile(name.Text, ID);
GuitarBrandsGridView.EditIndex = -1;
bindgridviewguitarbrands();
}
// cancel row edit event
protected void GuitarBrandsGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
string id = GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString();
TextBox name = (TextBox)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("TextBox2");
int ID = Convert.ToInt32(id);
ConnectionClassGuitarBrands.CreateGuitarBrandsDatabase(name.Text);
AddCodeToGuitarFile.AddGuitarClassCode(name.Text, ID);
AddCodeToGuitarFile.AddConnectionClassGuitarItems(name.Text);
AddCodeToGuitarFile.AddOverviewGuitarDataASPX(name.Text, ID);
AddCodeToGuitarFile.AddOverviewGuitarDataASPXCode(name.Text);
AddASPXAndCSFileForGuitarBrands.AddFile(name.Text,ID);
GuitarBrandsGridView.EditIndex = -1;
bindgridviewguitarbrands();
}
//End of Gridview Code for Guitar Brands
Hope you guys can help me on this one. Also, this is only for practice. I will implement better security in my website soon.
ADDED CODE: code is too long so i have removed some parts in AddCodeToGuitarFile
Here is the ConnectionClassGuitarBrands.cs:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for ConnectionClassGuitarBrands
/// </summary>
public static class ConnectionClassGuitarBrands
{
private static SqlConnection conn;
private static SqlCommand command;
static ConnectionClassGuitarBrands()
{
string connectionString =
ConfigurationManager.ConnectionStrings["brandsConnection"].ToString();
conn = new SqlConnection(connectionString);
command = new SqlCommand("", conn);
}
public static void CreateGuitarBrandsDatabase(string brand)
{
SqlConnection createBrandData = new SqlConnection(#"Data Source=Y560\SQLEXPRESS;Initial Catalog=GuitarItemsDB;Integrated Security=True");
createBrandData.Open();
SqlCommand cmdBrandData = new SqlCommand("CREATE TABLE guitarItem" + brand + "(id int,type char(50),model char(50),price float,image1 char(255),image2 char(255),description text, [neck type] char(100), body char(100), fretboard char(100), fret char(50), bridge char(100),[neck pickup] char(100), [bridge pickup] char(100), [hardware color] char(50)); ", createBrandData);
cmdBrandData.ExecuteNonQuery();
createBrandData.Close();
}
public static void RemoveGuitarBrandsDatabase(string brand)
{
SqlConnection removeBrandData = new SqlConnection(#"Data Source=Y560\SQLEXPRESS;Initial Catalog=GuitarItemsDB;Integrated Security=True");
removeBrandData.Open();
SqlCommand cmdBrandData = new SqlCommand("DROP TABLE guitarItem"+brand+";" , removeBrandData);
cmdBrandData.ExecuteNonQuery();
removeBrandData.Close();
}
public static ArrayList GetBrandsByType(string brandType)
{
ArrayList list = new ArrayList();
string query = string.Format("SELECT * FROM guitarBrands WHERE type LIKE '{0}'", brandType);
try
{
conn.Open();
command.CommandText = query;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int id = reader.GetInt32(0);
string name = reader.GetString(1);
string type = reader.GetString(2);
string image = reader.GetString(3);
Brands brand = new Brands(id, name, type, image);
list.Add(brand);
}
}
finally
{
conn.Close();
}
return list;
}
public static void AddGuitarBrands(Brands brands)
{
string query = string.Format(#"INSERT INTO guitarBrands VALUES ('{0}','{1}','{2}','{3}')", brands.Id, brands.Type, brands.Name, brands.Image);
command.CommandText = query;
try
{
conn.Open();
command.ExecuteNonQuery();
}
finally
{
conn.Close();
}
}
}
Here is the AddCodeToGuitarFile.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for AddCodeToGuitarFile
/// </summary>
public static class AddCodeToGuitarFile
{
static AddCodeToGuitarFile()
{
}
public static void AddGuitarClassCode(string brand_name, int brand_number)
{
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\AddGuitarClass.cs");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(" default:"))
{
break;
}
counter += 1;
}
file.Close();
var addGuitarLines = File.ReadAllLines(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\AddGuitarClass.cs");
var _addGuitarLines = new List<string>(addGuitarLines);
int index = counter;
index -= 1;
_addGuitarLines.Insert(index++, " case \"" + brand_name + "\":");
_addGuitarLines.Insert(index++, " string query" + brand_number + " = string.Format(\"INSERT INTO guitarItem" + brand_name + " VALUES ('{0}','{1}','{2}',#itemprice,'{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}')\",");
_addGuitarLines.Insert(index++, " gItems.Id, gItems.Brand, gItems.Model, gItems.Image1, gItems.Image2, gItems.Description, gItems.NeckType, gItems.Body,");
_addGuitarLines.Insert(index++, " gItems.Fretboard, gItems.Fret, gItems.Bridge, gItems.NeckPickup, gItems.BridgePickup, gItems.HardwareColor);");
_addGuitarLines.Insert(index++, "");
_addGuitarLines.Insert(index++, " command1.CommandText = query" + brand_number + ";");
_addGuitarLines.Insert(index++, " command1.Parameters.Add(new SqlParameter(\"itemprice\", gItems.Price));");
_addGuitarLines.Insert(index++, "");
_addGuitarLines.Insert(index++, " try");
_addGuitarLines.Insert(index++, " {");
_addGuitarLines.Insert(index++, " conn1.Open();");
_addGuitarLines.Insert(index++, " command1.ExecuteNonQuery();");
_addGuitarLines.Insert(index++, " }");
_addGuitarLines.Insert(index++, " finally");
_addGuitarLines.Insert(index++, " {");
_addGuitarLines.Insert(index++, " conn1.Close();");
_addGuitarLines.Insert(index++, " command1.Parameters.Clear();");
_addGuitarLines.Insert(index++, " }");
_addGuitarLines.Insert(index++, " break;");
_addGuitarLines.Insert(index++, "");
addGuitarLines = _addGuitarLines.ToArray();
File.WriteAllLines(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\App_Code\AddGuitarClass.cs", addGuitarLines);
}
}
You just need to modify your page_load event handler within aspx.cs like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
bindgridviewguitarbrands();
}
Because whenever you click on edit/delete button, it just refreshes the grid data and all the event data within grid is refreshed too. So, the grid events are binded again and thats why those events of edit/delete are not firing as per requirement.
I've tested your code, just this change will solve your issue.
Hope it helps.
I finally solved the problem. I thought at first, that when i delete something for the first time, it refreshes. But i've found out that it isn't. That's the reason why its not updating the gridview when i delete something for the second time. The answer to this problem is simply just Response.Redirect.
protected void GuitarBrandsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(GuitarBrandsGridView.DataKeys[e.RowIndex].Value.ToString());
Label name = (Label)GuitarBrandsGridView.Rows[e.RowIndex].FindControl("Label4");
con1.Open();
cmd1.CommandText = "DELETE FROM [guitarBrands] WHERE id=" + id;
cmd1.Connection = con1;
int a = cmd1.ExecuteNonQuery();
con1.Close();
if (a > 0)
{
bindgridviewguitarbrands();
}
RemoveCodeToGuitarFile.RemoveAddGuitarClass(name.Text);
RemoveCodeToGuitarFile.RemoveConnectionClassGuitarItems(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataASPX(name.Text);
RemoveCodeToGuitarFile.RemoveOverviewGuitarDataCode(name.Text);
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx");
File.Delete(#"C:\Users\User1\Documents\Visual Studio 2015\WebSites\MusicStore\Pages\GuitarItems" + id + ".aspx.cs");
ConnectionClassGuitarBrands.RemoveGuitarBrandsDatabase(name.Text);
Response.Redirect("url"); //The answer to this question
}
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.
I want to pass the query string value without redirecting to current page I have tried these code but I can even see the query string value variable to pass in these page.I have attached my code below.help me out from these problem
Thanks in advance
Aspx design code
<div class="col span_1_of_1">
<asp:GridView ID="gridweeks" runat="server" CssClass="grid" ShowHeaderWhenEmpty="True" ShowFooter="true" Style="width: 40%" AllowPaging="true" PageIndex="0" PageSize="5" AutoGenerateColumns="False" OnPageIndexChanging="gridweeks_PageIndexChanging">
<AlternatingRowStyle BackColor="#dddddd" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="weekmonth" HeaderText="Available Month" SortExpression="weekmonth" />
<asp:BoundField DataField="dayweek" HeaderText="Available Weeks" SortExpression="dayweek" />
<asp:TemplateField HeaderText="Edit / Delete">
<ItemTemplate>
<asp:LinkButton ID="lnkeditweek" runat="server" Style="color: black" CommandName="assign1" CommandArgument='<%#Eval("dayweek")+","+Eval("weekmonth")%>' OnClick="lnkeditweek_Click1"><i class="fa fa-pencil-square-o" style="color:#2389C9"></i></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#ffffff" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#32404E" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#32404E" ForeColor="White" HorizontalAlign="right" />
<RowStyle BackColor="#ffffff" BorderColor="#fff" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="batch" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT DISTINCT [dayweek], [weekmonth] FROM [tblslots]"></asp:SqlDataSource>
</div>
C# code
LinkButton btn = (LinkButton)(sender);
lbltxt.Visible = true;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
try
{
if (btn.CommandName == "assign1")
{
string[] commandArgs = btn.CommandArgument.ToString().Split(new char[] { ',' });
zeroval = commandArgs[0];
firstval = commandArgs[1];
for (int j = 0; j < gridweeks.Rows.Count; j++)
{
GridViewRow gw = gridweeks.Rows[j];
//string months = gw.Cells[0].Text;
// string weeks = gw.Cells[1].Text;
for (int i = 0; i < gridsem.Rows.Count; i++)
{
GridViewRow gs = gridsem.Rows[i];
string semester = gs.Cells[0].Text;
lbltxt.Text = "You are going to edit for Section : " + Request.QueryString["section"] + ", Week : " + zeroval + " , Session : " + Request.QueryString["session"] + " , Semester : " + semester + " , Month : " + firstval + "";
mp5edit.Show();
}
}
string longurl = "viewavailableweeks.aspx?&ins=" + Request.QueryString["ins"] + "§ion=" + Request.QueryString["section"] + "&session=" + Request.QueryString["session"] + "&academicyear=" + Request.QueryString["academicyear"] + "&month='" + firstval + "'+&week='" + firstval + "'";
var uriBuilder = new UriBuilder(longurl);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
longurl = uriBuilder.ToString();
}
}
I have created this gridview .This is my code
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList dropdownnop = (e.Row.FindControl("dropdownnop") as DropDownList);
dropdownnop.DataSource = obj6.Fetchdata("SELECT * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';");
dropdownnop.DataTextField = "DESC";
dropdownnop.DataValueField = "DESC";
dropdownnop.DataBind();
// Select the payment nature in DropDownList
string nop = (e.Row.FindControl("NOP") as Label).Text;
dropdownnop.Items.FindByValue(nop).Selected = true;
}
here's my html gridview code
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="Black" BorderStyle="Solid" Font-Bold="True" Font-Italic="False" Font-Size="Small" Height="72px" style="margin-left: 41px; margin-top: 108px" Width="783px" DataKeyNames="ID" OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" OnRowCancelingEdit="GridView1_RowCancelingEdit" AutoGenerateColumns="False" AllowPaging="True" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDataBound="OnRowDataBound">
<AlternatingRowStyle BackColor="#FFFFCC" BorderColor="#FF9900" Wrap="False" />
<Columns>
<asp:TemplateField HeaderText="TASK ID" SortExpression="TASK ID" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="TASKID" runat="server" Text='<%#Eval("[TASK ID]") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NATURE OF PAYMENT" SortExpression="NATURE OF PAYMENT" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="NOP" runat="server" Text='<%#Eval("[NATURE OF PAYMENT]") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownnop"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DESC" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="DESC" Text='<%#Eval("[DESC]") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID ="DESC" runat="server" Text='<%#Eval("[DESC]") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="REQUIREDFIELDVALIDATORDESC" runat="server" ControlToValidate="DESC" ErrorMessage="FIELD CANNOT BE EMPTY"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FREQUENCY" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="FREQUENCY" Text='<%#Eval("FREQUENCY") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownfreq"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DUE DATE OF PAYMENT" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="DDOP" Text='<%#Eval("PREALERT1") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownddop"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DUE DATE OF SUBMISSION OF RETURN" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="DDOSOR" Text='<%#Eval("PREALERT2") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownddosor"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="OWNER" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="OWNER" Text='<%#Eval("OWNER") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownowner"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="VERIFICATION OWNER" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="VO" Text='<%#Eval("[VERIFICATION OWNER]") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="dropdownvo"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="STATUS" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label runat="server" ID="STATUS" Text='<%#Eval("STATUS") %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat ="server" ID="dropdownstatus">
<asp:ListItem Text="Active" Value="1"></asp:ListItem>
<asp:ListItem Text="Inactive" Value="0"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false" HeaderText="ID">
<ItemTemplate>
<asp:Label runat="server" ID="ID" Text='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" HeaderStyle-BackColor="DarkGreen" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandName="Edit" />
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast" PageButtonCount="4" />
</asp:GridView>
So, my problem here is that Iam able to edit is using the edit events but I am not able to
populate the dropdown inside the gridview, whereas Iam able to do the same outside the GridView.
Here's my full codebehind
{
Comp obj6 = new Comp();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//populate gridview
TextBox2.Focus();
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.PopulateGrid(GridView1, selectquery);
{
// populate dropdownlist for prealert 1
for (int i = 0; i <= 30; i++)
{
DropDownList3.Items.Insert(i, new ListItem((i + 1).ToString(), (i + 1).ToString()));
}
DropDownList3.DataBind();
}
{
// populate dropdown list for prealert 2
for (int j = 0; j <= 30; j++)
{
DropDownList4.Items.Insert(j, new ListItem((j + 1).ToString(), (j + 1).ToString()));
}
DropDownList4.DataBind();
}
{
//populate dropdown for Nature of Payment
string query = "select * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';";
string columnname = "DESC";
string datavaluefield = "DESC";
obj6.PopulateCombo(DropDownList1, query, columnname, datavaluefield);
}
{
//populate dropdown for frequency
string query1 = "select * from Compliance_Tracker.dbo.frequencyMaster where STATUS='1';";
string columnname1 = "DESC";
string datavaluefield1 = "DESC";
obj6.PopulateCombo(DropDownList2, query1, columnname1, datavaluefield1);
}
{
//populate dropdown for owner
string query2 = "select * from Compliance_Tracker.dbo.ownerMaster where STATUS='1';";
string columnname2 = "NAME";
string datavaluefield2 = "NAME";
obj6.PopulateCombo(DropDownList5, query2, columnname2, datavaluefield2);
}
{
//populate dropdown for owner verification
string query3 = "select * from Compliance_Tracker.dbo.verificationMaster where STATUS='1'";
string columnname3 = "NAME";
string datavaluefield3 = "NAME";
obj6.PopulateCombo(DropDownList6, query3, columnname3, datavaluefield3);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string query = "insert into Compliance_Tracker.dbo.tasklistManager([NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],STATUS)values('" + DropDownList1.SelectedItem.Text + "','" + TextBox2.Text + "','" + DropDownList2.SelectedItem.Text + "','" + DropDownList3.SelectedItem.Text + "','" + DropDownList4.SelectedItem.Text + "','" + DropDownList5.SelectedItem.Text + "','" + DropDownList6.SelectedItem.Text + "','" + DropDownList7.SelectedValue + "');";
obj6.ExecuteScalar(query);
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.PopulateGrid(GridView1, selectquery);
TextBox2.Text = string.Empty;
DropDownList7.SelectedItem.Text = "Active";
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.bind(GridView1, selectquery, "Compliance_Tracker.dbo.tasklistManager");
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string ID = GridView1.DataKeys[e.RowIndex].Value.ToString();
string query = "delete Compliance_Tracker.dbo.tasklistManager where Compliance_Tracker.dbo.tasklistManager.ID = " + ID;
string populatequery = query + ";select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.BindGridData(populatequery, GridView1);
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.bind(GridView1, selectquery, "Compliance_Tracker.dbo.tasklistManager");
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
string selectquery = "select [TASK ID],[NATURE OF PAYMENT],[DESC],FREQUENCY,PREALERT1,PREALERT2,OWNER,[VERIFICATION OWNER],(case when STATUS='1' then 'Active' when STATUS='0' then 'Inactive' ELSE 'UNKNOWN' END)as STATUS,ID from Compliance_Tracker.dbo.tasklistManager;";
obj6.bind(GridView1, selectquery, "Compliance_Tracker.dbo.tasklistManager");
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Find the DropDownList in the Row
DropDownList dropdownnop = (e.Row.FindControl("dropdownnop") as DropDownList);
dropdownnop.DataSource = obj6.Fetchdata("SELECT * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';");
dropdownnop.DataTextField = "DESC";
dropdownnop.DataValueField = "DESC";
dropdownnop.DataBind();
// Select the payment nature in DropDownList
string nop = (e.Row.FindControl("NOP") as Label).Text;
dropdownnop.Items.FindByValue(nop).Selected = true;
}
}
And here's the fetchdata code
public DataTable Fetchdata(string strSQL)
{
SqlDataAdapter DAdpt = new SqlDataAdapter();
DataSet DSet = new DataSet();
try
{
if (Conn.State == ConnectionState.Closed)
Conn.Open();
DAdpt = new SqlDataAdapter(strSQL, Conn);
DAdpt.Fill(DSet);
return DSet.Tables[0];
}
catch (Exception Ex)
{
return null;
throw new Exception(Ex.Message);
}
finally
{
DAdpt.Dispose();
DSet.Dispose();
Conn.Close();
}
}
Must be some problem with find control code. Try the one I have using in the code given below :
protected void GrdPDataEdit_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Replace your find corntrol code with this
DropDownList drpnop = (DropDownList)e.Row.FindControl("dropdownnop");
if (drpnop != null)
{
drpnop.DataSource = obj6.Fetchdata("SELECT * from Compliance_Tracker.dbo.paymentNatureMaster where STATUS='1';");
drpnop.DataTextField = "DESC";
drpnop.DataValueField = "DESC";
drpnop.DataBind();
}
}
}
You can't directly access the DropDownList inside of the GridView while the gridview is being generated. What you'll have to do is to use the GridView OnRowCreated event and populate the dropdown that way. I don't have any sample code handy, but there are a ton of references on the internet.
Most of your code is usable, but you'll need to move a few things around.
Basically you'll need to create an event for OnRowCreated and then - this is the key part - use the FindControl method to find the DropDownList and finally insert the items into the DDL.
Clarification: I thought your code in the OnLoad was trying to populate the DDL and I didn't see the code box scrolled down. Looks like your code is solid, I think you just need to switch from OnRowBinding to OnRowCreated