what is the command of select in grid view asp.net - c#

I have a GridView called gridview1
What I want is that if the user select or click on specific row some action will happen.
For example I want to get the value from that row and store it in a new variable.
How can I do it? I'm confused about what I should do to get the value?
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
string stuId = ?
}

<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
AutoGenerateColumns="false" OnSelectedIndexChanged = "OnSelectedIndexChanged">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField Text="Select" CommandName="Select" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<br />
<u>Selected Row Values: </u>
<br />
<br />
<asp:Label ID="lblValues" runat="server" Text=""></asp:Label>
aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
//Accessing BoundField Column
string name = GridView1.SelectedRow.Cells[0].Text;
//Accessing TemplateField Column controls
string country = (GridView1.SelectedRow.FindControl("lblCountry") as Label).Text;
lblValues.Text = "<b>Name:</b> " + name + " <b>Country:</b> " + country;
}
you simply copy and paste your issue is resolve.

you could use like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"
OnRowCommand = "OnRowCommand">
<Columns>
<asp:ButtonField CommandName = "ButtonField" DataTextField = "StudID"
ButtonType = "Button"/>
</Columns>
</asp:GridView>
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
}

Related

How can i add pagination to a parent gridview using asp.net c#?

i am stuck in a situation where i need to add pagination to parent gridview only(I have a nested gridview where i don't want to add paginatiion to child gridview).i have searched for many example but however I couldn't find any solution.Please help me with this. I am stuck on this issue and could not find any workaround.i am getting input string was not in correct format error on rowcommand event on line
int id = int.Parse(e.CommandName.ToString());
<asp:GridView ID="GVLeader" runat="server" AutoGenerateColumns="false"
DataKeyNames="id" OnRowCommand="GVLeader_RowCommand"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-
CssClass="alt" PageSize = "15" AllowSorting="true"
AllowPaging="true">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#
Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" >
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#
Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#
Eval("Name") %>' Width="100"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Detail View" ControlStyle-
BackColor="#EBEBEB">
<ItemTemplate>
<asp:Button runat="server" ID="btnplus" Text="Edit Details"
CssClass="greenButton" CommandName='<%#Eval("id") %>'
CommandArgument='<%#Container.DataItemIndex%>' />
<asp:GridView ID="GVMember" AutoGenerateColumns="false"
runat="server" AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
DataKeyNames="id"
OnRowCancelingEdit="GVMember_RowCancelingEdit"
OnRowEditing="GVMember_RowEditing" OnRowDeleting="OnRowDeleting"
OnRowUpdating="GVMember_RowUpdating"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-
CssClass="alt" PageSize = "10" AllowSorting="true"
AllowPaging="true">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#
Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp Salary" >
<ItemTemplate>
<asp:Label ID="lblEmpSalary" runat="server" Text='<%#
Eval("EmpSalary") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmpSalary" runat="server" Text='<%#
Eval("EmpSalary") %>' Width="100"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp Address " >
<ItemTemplate>
<asp:Label ID="lblEmpAddress" runat="server" Text='<%#
Eval("Emp Address") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmpAddress" runat="server" Text='<%#
Eval("Emp Address") %>' Width="100"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CodeBehind Code:-
namespace Final
{
public partial class test : System.Web.UI.Page
{
SqlConnection con = new
SqlConnection(ConfigurationSettings.AppSettings["server"].ToString());
SqlConnection con1 = new SqlConnection("confidential"); //Create
sqlconnection
SqlDataAdapter da;
DataTable dt2, dt1;
Properties objlog = new Properties();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGVLeader();
}
}
protected void GVLeader_RowCommand(object sender,
GridViewCommandEventArgs e)
{
int id = int.Parse(e.CommandName.ToString());
int rowindex = int.Parse(e.CommandArgument.ToString());
GridView GVMember =
(GridView)GVLeader.Rows[rowindex].FindControl("GVMember");
Button btn =
((Button)GVLeader.Rows[rowindex].FindControl("btnplus"));
if (btn.Text == "Edit Details")
{
btn.Text = "Cancel";
GVMember.DataSource = LoadGVMember(id);
GVMember.DataBind();
GVMember.Visible = true;
}
else
{
btn.Text = "Edit Details";
GVMember.Visible = false;
}
}
public void LoadGVLeader()
{
da = new SqlDataAdapter("select * from emptable", con);
dt = new DataTable();
da.Fill(dt);
GVLeader.DataSource = dt;
GVLeader.DataBind();
}
protected DataTable LoadGVMember(int id)
{
da = new SqlDataAdapter("select * from emptable where ID=" + id,
con);
dt1 = new DataTable();
da.Fill(dt1);
ViewState["dt"] = dt1;
return dt1;
}
protected void GVMember_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
int id =
int.Parse(GVLeader.DataKeys[gvrow.RowIndex].Value.ToString());
Gv.EditIndex = e.NewEditIndex;
Gv.DataSource = LoadGVMember(id);
Gv.DataBind();
}
protected void GVMember_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
int id =
int.Parse(GVLeader.DataKeys[gvrow.RowIndex].Value.ToString());
Gv.EditIndex = -1;
Gv.DataSource = LoadGVMember(id);
Gv.DataBind();
}
protected void GVMember_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
int id =
int.Parse(GVLeader.DataKeys[gvrow.RowIndex].Value.ToString());
int id1 = int.Parse(Gv.DataKeys[e.RowIndex].Value.ToString());
Gv.EditIndex = -1;
Gv.DataSource = LoadGVMember(id);
Gv.DataBind();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
Label lbldeleteid = (Label)gvrow.FindControl("lblID");
con.Open();
SqlCommand cmd = new SqlCommand("delete FROM emptable where ID='" +
Convert.ToInt32(GVLeader.DataKeys[e.RowIndex].Value.ToString()) + "'",
con);
cmd.ExecuteNonQuery();
con.Close();
LoadGVLeader();
}
}
}
remove pagination props from child grid(GVMember)
change
<asp:GridView ID="GVMember" AutoGenerateColumns="false"
runat="server" AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
DataKeyNames="id"
OnRowCancelingEdit="GVMember_RowCancelingEdit"
OnRowEditing="GVMember_RowEditing" OnRowDeleting="OnRowDeleting"
OnRowUpdating="GVMember_RowUpdating"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-
CssClass="alt" PageSize = "10" AllowSorting="true"
AllowPaging="true">
with
<asp:GridView ID="GVMember" AutoGenerateColumns="false"
runat="server" AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
DataKeyNames="id"
OnRowCancelingEdit="GVMember_RowCancelingEdit"
OnRowEditing="GVMember_RowEditing" OnRowDeleting="OnRowDeleting"
OnRowUpdating="GVMember_RowUpdating"
CssClass="mGrid" AlternatingRowStyle-
CssClass="alt" AllowSorting="true">

Populate DropDownList inside template field in GridView with data from CodeBehind

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

dropdownlist name has a SelectedValue which is invalid because it does not exist in the list of items

What I want to achieve is when I click on edit, the Blogtype field in the gridview will be changed to dropdownlist. And Since my database have 3 data in the blogtype which is community work, competition and overseas experience. The dropdownlist will be allows me to select either of these three. After choosing either of this one, and I clicked update, it will be updated in the database. How to do it as I have error in the 3rd screenshot.The name of my dropdownlist for blogtype field is ddlBlogType. help
But for my current code, after clicking edit, it will come out this error. 'ddlBlogType' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Source Code
<asp:GridView ID="grdBlog" runat="server" style=
"margin-left: 0px" Width="1000px" Height="147px" AutoGenerateColumns="False"
onrowcancelingedit="grdBlog_RowCancelingEdit" onrowediting="grdBlog_RowEditing"
onrowupdating="grdBlog_RowUpdating" DataKeyNames="BlogID"
onrowdeleting="grdBlog_RowDeleting" AllowPaging="True"
onpageindexchanging="grdBlog_PageIndexChanging" PageSize="5"
BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px"
CellPadding="3" CellSpacing="1" GridLines="None" >
<Columns>
<asp:BoundField DataField="BlogID" HeaderText="BlogID" ReadOnly="true"
SortExpression="BlogID" />
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Width="80px" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="BlogType">
<EditItemTemplate>
<asp:DropDownList ID="ddlBlogType" runat="server" Width="80px" Text='<%# Bind("BlogType") %>'></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("BlogType") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<EditItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" Width="80px" Text='<%# Bind("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DateEntry" HeaderText="Date Entry" ReadOnly="true" />
<asp:TemplateField HeaderText="Blog Story">
<EditItemTemplate>
<asp:TextBox ID="txtBlogStory" runat="server" TextMode="multiline" rows="10" Text='<%# Bind("BlogStory") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("BlogStory") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="modifiedby" HeaderText="Last Modified By" ReadOnly="true" />
<asp:BoundField DataField="modifieddate" HeaderText="Last Modified Date" ReadOnly="true" />
<asp:CommandField ShowEditButton="True" CausesValidation="false" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="javascript : return confirm('Confirm delete this record?');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#594B9C" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#33276A" />
</asp:GridView>
Code Behind Code
if (Page.IsPostBack == false)
{
bindResultGridView();
}
private void bindResultGridView()
{
String ConStr = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(ConStr);
try
{
String SQL = null;
SQL = "SELECT BlogID, Name, Blogtype, Description, convert(varchar,Dateentry, 103) as Dateentry, BlogStory, modifiedby, convert(varchar,modifieddate, 103) as modifieddate FROM [EntryTable] ORDER BY BlogID DESC";
SqlCommand cmd = new SqlCommand(SQL, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
grdBlog.DataSource = dt;
grdBlog.DataBind();
reader.Close();
}
finally
{
con.Close();
}
}
protected void grdBlog_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grdBlog.EditIndex = -1;
bindResultGridView();
}
protected void grdBlog_RowEditing(object sender, GridViewEditEventArgs e)
{
grdBlog.EditIndex = e.NewEditIndex;
bindResultGridView();
}
protected void grdBlog_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int selectedRow = e.RowIndex; //get selected row
// get product id from data key
int blogid = (int)grdBlog.DataKeys[selectedRow].Value;
// get current grid view row
GridViewRow row = (GridViewRow)grdBlog.Rows[selectedRow];
TextBox name = (TextBox)row.FindControl("txtName");
// find text box for txtPrice
DropDownList blogtype = (DropDownList)row.FindControl("ddlBlogType");
TextBox description = (TextBox)row.FindControl("txtDescription");
TextBox blogstory = (TextBox)row.FindControl("txtBlogStory");
// Remove $ sign
string strName = name.Text;
string strBlogType = blogtype.Text;
string strDescription = description.Text;
string strBlogStory = blogstory.Text;
/*
DateTime datDate;
*/
/*
if (DateTime.TryParseExact(strDateEntry, new string[] { "dd/MM/yyyy" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out datDate))
{
*/
updateBlogGridviewRecord(blogid, strName, strBlogType, strDescription, strBlogStory);
/*
}
else
{
lblError.Visible = true;
lblError.Text = "Invalid Date";
lblSuccess.Visible = false;
}
*/
}
private void updateBlogGridviewRecord(int blogid, string strName, string strBlogType, string strDescription, string strBlogStory)
{
try
{
string strConnectionString = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "UPDATE EntryTable SET [ModifiedBy]=#Modifier, [ModifiedDate] = GETDATE(), [Name]=#Name, [BlogType]=#BlogType, [Description]=#Description, [BlogStory]=#BlogStory WHERE [BlogID]=#BlogID";
/*string strCommandText = "UPDATE EntryTable SET [Name]=#Name, [BlogType]=#BlogType, [Description]=#Description, [DateEntry]=#DateEntry, [BlogStory]=#BlogStory WHERE [BlogID]=#BlogID"; */
/*string strCommandText = "UPDATE EntryTable SET [ModifiedBy] = [Name], [Name]=#Name, [BlogType]=#BlogType, [Description]=#Description, [DateEntry]=#DateEntry, [BlogStory]=#BlogStory WHERE [BlogID]=#BlogID"; */
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
cmd.Parameters.AddWithValue("#BlogID", blogid);
cmd.Parameters.AddWithValue("#Name", strName);
cmd.Parameters.AddWithValue("#BlogType", strBlogType);
//cmd.Parameters.AddWithValue("#DateEntry", datDate);
cmd.Parameters.AddWithValue("#Description", strDescription);
cmd.Parameters.AddWithValue("#BlogStory", strBlogStory);
cmd.Parameters.AddWithValue("#Modifier", Session["Username"]);
myConnect.Open();
int result = cmd.ExecuteNonQuery();
if (result > 0)
{
lblSuccess.Visible = true;
lblSuccess.Text = "Record updated!";
lblError.Visible = false;
}
else
{
lblSuccess.Visible = true;
lblError.Text = "Update fail";
lblError.Visible = false;
}
myConnect.Close();
//Cancel Edit Mode
grdBlog.EditIndex = -1;
bindResultGridView();
}
catch
{
lblError.Visible = true;
lblError.Text = "Invalid Data";
lblSuccess.Visible = false;
}
}
Did it using the edited code below
Source Code
<asp:TemplateField HeaderText="BlogType">
<EditItemTemplate>
<asp:DropDownList ID="ddlBlogType" runat="server" DataTextField="ddlBlogType" DataValueField="ddlBlogType" SelectedValue='<%# Eval("blogType") %>'>
<asp:ListItem Enabled="true" Text="Community Work" Value="Community Work"></asp:ListItem>
<asp:ListItem Text="Competition" Value="Competition"></asp:ListItem>
<asp:ListItem Text="Overseas Experience" Value="Overseas Experience"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("BlogType") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Code behind Code
protected void grdBlog_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int selectedRow = e.RowIndex; //get selected row
// get product id from data key
int blogid = (int)grdBlog.DataKeys[selectedRow].Value;
// get current grid view row
GridViewRow row = (GridViewRow)grdBlog.Rows[selectedRow];
TextBox name = (TextBox)row.FindControl("txtName");
// find text box for txtPrice
DropDownList blogtype = (DropDownList)row.FindControl("ddlBlogType");
TextBox description = (TextBox)row.FindControl("txtDescription");
TextBox blogstory = (TextBox)row.FindControl("txtBlogStory");
// Remove $ sign
string strName = name.Text;
string strBlogType = blogtype.SelectedValue;
string strDescription = description.Text;
string strBlogStory = blogstory.Text;
}
I see the issue as the way you populate the DropDownList. The code isn't shown in your post, so assuming you don't have anything to that effect.
So you normally set the desired gridviewrow in edit mode as below:
protected void grdBlog_RowEditing(object sender, GridViewEditEventArgs e)
{
grdBlog.EditIndex = e.NewEditIndex;
bindResultGridView();
}
Now we need to figure when exactly to bind the dropdownlist. Therefore when the particular datarow (which is in edit mode) is getting databound we have a chance to obtain the reference to the corresponding edit row's dropdownlist. Hence for this you can refer this post.
In summary you need to handle the DataBound event of the gridview and determine from its rowstate what mode it is in. Sharing the code sample from linked post below:
protected void gv_RowDataBound(object sender, GridViewEditEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddList= (DropDownList)e.Row.FindControl("DStatusEdit");
//bind dropdownlist
DataTable dt = con.GetData("select distinct status from directory");
ddList.DataSource = dt;
ddList.DataTextField = "YourCOLName";
ddList.DataValueField = "YourCOLName";
ddList.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
//ddList.SelectedItem.Text = dr["YourCOLName"].ToString();
ddList.SelectedValue = dr["YourCOLName"].ToString();
}
}
}

Gridview Paging is not working when i use it in content place holder?

I dont know why paging is not working when i use master page. If I put the same code in another file which in not linked with master page it works like a charm. But when I link it to master page it doesn't work.
here is my mark up
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div id="menu_content">
<div class="tabs">
My Addresses</div>
<div class="midContent">
<asp:GridView ID="addressGrd" OnPageIndexChanging="addressGrd_PageIndexChanging"
Width="816px" ForeColor="#ffffff" AllowSorting="true" HeaderStyle-BackColor="#222222"
HeaderStyle-Height="60px" runat="server" AutoGenerateColumns="False" GridLines="None"
AllowPaging="True" PagerSettings-FirstPageText="First" PagerSettings-LastPageText="Last"
PagerSettings-Mode="NextPreviousFirstLast" PageSize="5" PagerSettings-PageButtonCount="4">
<Columns>
<asp:BoundField DataField="customerName" HeaderText="Name" ReadOnly="True" />
<asp:BoundField DataField="customerCompany" HeaderText="Company" ReadOnly="True" />
<asp:BoundField DataField="customerPhone" HeaderText="Phone" ReadOnly="True" />
<asp:BoundField DataField="addressLine1" HeaderText="Address 1" ReadOnly="True" />
<asp:BoundField DataField="addressLine2" HeaderText="Address 2" ReadOnly="True" />
<asp:BoundField DataField="city" HeaderText="City" ReadOnly="True" />
<asp:BoundField DataField="state" HeaderText="State" ReadOnly="True" />
<asp:BoundField DataField="zipCode" HeaderText="Zip Code" ReadOnly="True" />
<asp:TemplateField>
<HeaderTemplate>
Main Address
</HeaderTemplate>
<ItemTemplate>
<asp:ImageButton runat="server" OnClick="changeStatus" ID="imgStatus" CommandArgument='<%#Eval("mainAddress")+","+ Eval("addressID")%>'
ImageUrl='<%# Bind_Image(Eval("mainAddress").ToString()) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Action
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="editItem" Text=" " OnClick="Edit" CommandArgument='<%# Eval("addressID")%>'
CssClass="editButton" runat="server">
</asp:LinkButton>
<asp:LinkButton Text=" " ID="deleteItem" CssClass="deleteButton"
runat="server" CommandArgument='<%# Eval("addressID")%>' OnClientClick="return confirm('Do You Want To Delete ?')"
OnClick="Delete">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings Mode="NumericFirstLast" PageButtonCount="4" FirstPageText="First"
LastPageText="Last" />
<PagerStyle BackColor="#222222" Height="30px" VerticalAlign="Bottom" HorizontalAlign="Center" />
<RowStyle Height="50px" BackColor="#117186" />
<AlternatingRowStyle BackColor="#0b4d5b" />
</asp:GridView>
<div style="float:right; margin-bottom:20px; margin-right:20px"><input type="button" class="buttonEffect" value="Register New Address" /></div>
</div>
</div>
and here is my code behind.
retrievedata3ct rd3ct;
DataTable dt;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
rd3ct = new retrievedata3ct();
dt = new DataTable();
ds = new DataSet();
if (!this.IsPostBack)
{
addAddresses();
}
}
public void addAddresses()
{
rd3ct = new retrievedata3ct();
ds = new DataSet();
ds = rd3ct.addressesSelection("", "");
addressGrd.DataSource = ds.Tables[0];
addressGrd.DataBind();
addressGrd.Visible = true;
//ScriptManager.GetCurrent(this).RegisterPostBackControl(addressGrd);
}
public string Bind_Image(string Status)
{
bool status = Convert.ToBoolean(Status);
if (status)
{
return "adminCP/resources/images/icons/tick_circle.png";
}
else
{
return "adminCP/resources/images/icons/cross_circle.png";
}
}
protected void addressGrd_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
addressGrd.PageIndex = e.NewPageIndex;
addAddresses();
}
protected void Delete(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
string ds = "";
ds = rd3ct.addressesDeletion(lnkRemove.CommandArgument);
if (ds == "OK")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Record Deleted.');", true);
addAddresses();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error Occurred.');", true);
}
}
protected void Edit(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
Session["addressID"] = "";
Session["addressID"] = lnkRemove.CommandArgument;
Response.Redirect("editAddresses.php5", false);
}
protected void changeStatus(object sender, EventArgs e)
{
string ds = "";
ImageButton ib = (ImageButton)sender;
string[] commandArgs = ib.CommandArgument.ToString().Split(new char[] { ',' });
string status = commandArgs[0];
string id = commandArgs[1];
if (status == "True")
{
ds = rd3ct.addressesStatusUpdate(id, "False");
if (ds == "OK")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Status Disabled.');", true);
addAddresses();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error Occurred.');", true);
}
}
else
{
ds = rd3ct.addressesStatusUpdate(id, "True");
if (ds == "OK")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Status Enabled.');", true);
addAddresses();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error Occurred.');", true);
}
}
}
Please help me out. Any help would be highly appreciated.
Have you tried to create an empty master page to put the content into? I suspect your master page is breaking the GridView.
Problem Solved.
Actually button name was conflicting in grid view.
I was having a button and its ID was 'submit' and in my another page there was also a button named with the same ID. thats why gridview paging was not working.
R.I.P Coding.. :)

Textbox In gridview not saving its value in table

I have a gridview gv_Products and a gridview Gv_selected. My products gridview has a checkbox that when is checked the selected row is entered in the gv_selected gridview.
I have added a textbox in gv_selected gridiew to enter the quantity i want to reorder. The quantity that i enter loses its value after i press the submit button.
<asp:GridView ID="gvSelected" runat="server"
AutoGenerateColumns = "False" Font-Names = "Arial" CssClass="gridviewsSmall" Font-Size = "11pt"
OnRowDataBound="GridView_gvSelected_RowDataBound" EnableViewState="False"
EmptyDataText = "No Records Selected" >
<Columns>
<asp:BoundField DataField="ProductId" HeaderText="Product ID" ReadOnly="True"
SortExpression="ProductId" />
<asp:TemplateField HeaderText="Product No" SortExpression="ProductNo">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("ProductNo") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Name" SortExpression="Product_name">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Product_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="SupplierId" HeaderText="Supplier ID" ReadOnly="True"
SortExpression="SupplierId" />
<asp:TemplateField HeaderText="Quantity" SortExpression="Quantity">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#Bind("Quantity") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnSendOrder" Visible="false" runat="server" Text="Send Order"
onclick="btnSendOrder_Click" />
Here is my code behind for adding rows in gvSelected gridview
private DataTable CreateDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("ProductId");
dt.Columns.Add("ProductNo");
dt.Columns.Add("Product_name");
dt.Columns.Add("SupplierId");
dt.Columns.Add("Quantity");
dt.AcceptChanges();
return dt;
}
private DataTable AddRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("ProductId = '" + gvRow.Cells[3].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["ProductId"] = gvRow.Cells[3].Text;
dt.Rows[dt.Rows.Count - 1]["ProductNo"] = (gvRow.FindControl("Label2") as Label).Text;
dt.Rows[dt.Rows.Count - 1]["Product_name"] = (gvRow.FindControl("Label3") as Label).Text;
dt.Rows[dt.Rows.Count - 1]["SupplierId"] = (gvRow.FindControl("Label5") as Label).Text;
dt.Rows[dt.Rows.Count - 1]["Quantity"] = 0;
dt.AcceptChanges();
}
return dt;
}
protected void CheckBox_CheckChanged(object sender, EventArgs e)
{
GetData();
SetData();
BindSecondaryGrid();
}
private void BindSecondaryGrid()
{
DataTable dt = (DataTable)ViewState["SelectedRecords"];
gvSelected.DataSource = dt;
gvSelected.DataBind();
}
And here is the submit button!
protected void btnSendOrder_Click(object sender, EventArgs e)
{
t_supplier_orders newOrder = new t_supplier_orders();
newOrder.UserName = User.Identity.Name;
newOrder.Order_date = DateTime.Now;
newOrder.Order_status = "Pending";
MembershipUser myObject = Membership.GetUser();
Guid UserID = new Guid(myObject.ProviderUserKey.ToString());
newOrder.UserId = UserID;
newOrder.SupplierId = Convert.ToInt32(ddl1.SelectedValue);
newOrder.Received_date = null;
Bohemian.t_supplier_orders.AddObject(newOrder);
Bohemian.SaveChanges();
//------------------------------------------------------------------------+
// Create a new OderDetail Record for each item in the gvSelected |
//------------------------------------------------------------------------+
foreach (GridViewRow row in gvSelected.Rows)
{
{
t_supplier_orders_details od = new t_supplier_orders_details();
TextBox txt1 = (TextBox)gvSelected.FindControl("TextBox1");
od.OrderId = newOrder.OrderId;
od.ProductId = Convert.ToInt32(row.Cells[0].Text);
od.Product_name = (row.FindControl("Label3") as Label).Text;
od.ProductNo = (row.FindControl("Label2") as Label).Text;
od.Quantity = Convert.ToInt32(txt1.text);
Bohemian.t_supplier_orders_details.AddObject(od);
}
}
Bohemian.SaveChanges();
lblSuccess.Text = "The Order has been successfully sent to supplier!!";
lblSuccess.ForeColor=System.Drawing.Color.BlueViolet;
lblSuccess.Font.Bold = true;
}
I assume that you are assigning the DataSource and DataBind the GridView on every postback. That will overwite all changes.
So wrap your code in a !IsPostBack check:
protected void Page_Load()
{
if(!IsPostBack)
{
BindSecondaryGrid();
}
}
By the way, you should not store the DataTable in ViewState since that will blow it up.

Categories