problem populating dropdownlist of gridview - c#

OnRowDataBound="grdViewCInfo_RowDataBound"
>
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="Concert Name" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="150px" ItemStyle-Wrap="true">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#Bind("Concert_Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#Bind("Concert_Name") %>'></asp:TextBox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center" Height="40px"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="150px" ItemStyle-Wrap="true">
<ItemTemplate>
<asp:Label ID="lblAddr" runat="server" Text='<%#Bind("Address") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAddr" runat="server" Text='<%#Bind("Address") %>'></asp:TextBox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center" Height="40px"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="City" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%#Bind("City") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCity" runat="server" Text='<%#Bind("City") %>'></asp:TextBox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Pincode" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblPincode" runat="server" Text='<%#Bind("Pincode") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPincode" runat="server" Text=' <%#Bind("Pincode") %>'></asp:TextBox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblcountry" runat="server" Text='<%#Bind("Country") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlCountry" runat="server" >
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Concert Date and Time" HeaderStyle-HorizontalAlign="Center"
ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblDateTime" runat="server" Text='<%#Bind("Concert_Date") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDateTime" runat="server" Text='<%#Bind("Concert_Date") %>'></asp:TextBox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" CausesValidation="False">
<ItemStyle Width="50px" />
</asp:CommandField>
<asp:CommandField ShowDeleteButton="true">
<ItemStyle Width="50px" />
</asp:CommandField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>

A part of this should be done at RowDataBound also.
Here is some sample code
private static DataSet ds;
private const string query = "select * from tblcountrynames";
protected void grdViewCInfo_RowEditing(object sender, GridViewEditEventArgs e)
{
grdViewCInfo.EditIndex = e.NewEditIndex;
//guessing that this is your databind event
dbLoad();
}
protected void grdViewCInfo_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit)
{
//your ddl
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlCountry");
PopulateCountries(ddl, query);
//grdViewCInfo.Rows[e.NewEditIndex].Cells[4].Controls.Add(ddl);
}
}
private void PopulateCountries(DropDownList ddl, string query)
{
if(ds!= null && ds.Tables[0].Rows.Count >0)
MySqlConnection objMycon1 = new MySqlConnection(strProvider);
//commenting open; as adapter doesn't need connection to be open
//objMycon1.Open();
MySqlCommand cmd1 = new MySqlCommand(query, objMycon1);
MySqlDataAdapter da = new MySqlDataAdapter(cmd1);
ds = new DataSet();
da.Fill(ds);
objMycon1.Close();
objMycon1.Dispose();//comment if objMycon1 is not IDisposible
}
if (ds.Tables[0].Rows.Count > 0)
{
ddl.DataSource = ds;
ddl.DataTextField = "Name";
ddl.DataValueField = "ID";
ddl.DataBind();
}
}
This is how it should be done.
Hope this helps.

What does (DropDownList)grdViewCInfo.Rows[e.NewEditIndex].Cells[4].FindControl("ddlCountry"); return , is ddl set?
I reckon not. Perhaps there is no "ddlCountry" control in that cell.
Its a curious coincidence that the line,
//grdViewCInfo.Rows[e.NewEditIndex].Cells[4].Controls.Add(ddl);
is commented out below.

Do you have a drop down list in your EditItemTemplate?
Edit: I don't think you are actually in edit mode in the RowEditing event. If you move your code down to the RowCommand,
Then check for the Edit command. Wrap your code in something like,
if(e.CommandName == "Edit")
{
// do your edit here.
}
Though keep your grdViewCInfo.EditIndex = e.NewEditIndex; line, as you need that there.

Related

How to make grid view footer controls visible if grid view is empty

I have a grid view control in my page that indexes all the Lecture Contents. I have added a Text Box control and a Link Button. But for the Lectures that have no Content yet, the Grid View does not appear.
Have tried many references, as a result the footer has appeared but I am not able to insert data using the Controls in the footer.
My main objective is to make the Controls behave same in both scenarios.
Here is the Grid View Code.
`<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EmptyDataText="No Contents found for this lecture." ShowFooter="true" HeaderStyle-Wrap="false" Width="70%" CssClass="Grid" AlternatingRowStyle-CssClass="alt" PagerStyle-CssClass="pgr" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText=" LectureID " SortExpression="lecc_id">
<ItemTemplate>
<asp:Label ID="lbllecc_id" runat="server" Text='<%# Bind("lecc_id") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lbllecc_id" runat="server" T`enter code here`ext="Create New">
</asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=" Content " SortExpression="lecc_contents">
<EditItemTemplate>
<asp:TextBox ID="tblecc_contents" runat="server" Text='<%# Bind("lecc_contents") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lbllecc_contents" runat="server" Text='<%# Bind("lecc_contents") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtcontent" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfcontent" runat="server" ErrorMessage="Content field cannot be blank." ControlToValidate="txtcontent" Text="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:LinkButton ID="createcontent" runat="server" OnClick="createcontent" CssClass="btn-sm btn-default">Insert Content</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</EmptyDataTemplate>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" Font-Size="17px" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" Font-Bold="False" Font-Size="14px" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>`
and the code behind functions for grid view.
`protected void Page_Load(object sender, EventArgs e){
if (Session["fac_username"] != null)
{
String username = Convert.ToString(Session["fac_username"]);
if (!IsPostBack)
{
BindGridViewData();
}
}
else
{
Response.Redirect("~/Account/Login.aspx");
}
}protected void BindGridViewData(){
int lecID = Convert.ToInt32(Session["lecID"]);
GridView1.DataSource = DataAccessLayer.getAllContents(lecID);
GridView1.DataBind();} protected void GridView1_SelectedIndexChanged(object sender, EventArgs e){
}
protected void createcontent(object sender, EventArgs e){
int lecID = Convert.ToInt32(Session["lecID"]);
con.Open();
SqlCommand command = new SqlCommand("insert into uni_lect_content(lecc_id, lecc_contents) values(#lecc_id, #lecc_contents)", con);
command.Parameters.AddWithValue("#lecc_id", lecID);
command.Parameters.AddWithValue("#lecc_contents", ((TextBox)GridView1.FooterRow.FindControl("txtcontent")).Text);
command.ExecuteNonQuery();
con.Close();
lblmsg.Text = "New Course Successfully Created..!";}`
DataAccessLayer class's getAllConents() method is here.
`public class AllContents
{
public long lecc_id { get; set; }
public string lecc_contents { get; set; }
}
public class DataAccessLayer
{
public static List<AllContents> getAllContents( int lecID){
List<AllContents> listAll = new List<AllContents>();
string cs = ConfigurationManager.ConnectionStrings["ILMSConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand com = new SqlCommand("select lecc_id, lecc_contents from uni_lect_content, uni_lectures, uni_offered_courses where uni_lect_content.lecc_id = uni_lectures.lec_id and uni_lectures.cours_offer_id = uni_offered_courses.cours_offer_id and lecc_id = '"+lecID+"'", con);
con.Open();
SqlDataReader rdr = com.ExecuteReader();
while (rdr.Read())
{
AllContents obj = new AllContents();
obj.lecc_id = Convert.ToInt32(rdr["lecc_id"]);
obj.lecc_contents = rdr["lecc_contents"].ToString();
listAll.Add(obj);
}
}
return listAll;
}`
Help me out of this situation.
Thanks in advance.
FRONT END GRDIVIEW
<asp:GridView ID="grdview" ShowFooter="true" OnRowEditing="grdview_RowEditing" OnRowCancelingEdit="grdview_RowCancelingEdit" OnRowCommand="grdview_RowCommand" OnRowUpdating="grdview_RowUpdating" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="SR No.">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
<asp:Label ID="lblid" runat="server" Text='<%#Eval("Id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Emp Name">
<ItemTemplate>
<asp:Label ID="elblempname" runat="server" Text='<%#Eval("EmpName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempname" runat="server" Text='<%#Eval("EmpName") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempname" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Emp No">
<ItemTemplate>
<asp:Label ID="elblempno" runat="server" Text='<%#Eval("EmpNo") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempno" runat="server" Text='<%#Eval("EmpNo") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempno" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Email">
<ItemTemplate>
<asp:Label ID="elblempemail" runat="server" Text='<%#Eval("Email_Id") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempemail" runat="server" Text='<%#Eval("Email_Id") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempemail" runat="server" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center" HeaderText="Age">
<ItemTemplate>
<asp:Label ID="elblempage" runat="server" Text='<%#Eval("Age") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="etxtempage" runat="server" Text='<%#Eval("Age") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftxtempage" runat="server" ></asp:TextBox>
<asp:Button ID="btnAdd" CommandName="AddNew" runat="server" Text="Add" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
BACKEND CODE
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
grdview.DataSource = ds;
grdview.DataBind();
int columncount = grdview.Rows[0].Cells.Count;
grdview.Rows[0].Cells.Clear();
grdview.Rows[0].Cells.Add(new TableCell());
grdview.Rows[0].Cells[0].ColumnSpan = columncount;
grdview.Rows[0].Cells[0].Text = "No Records Found";
if (e.CommandName == "AddNew")
{
TextBox ftxtempname = (TextBox)grdview.FooterRow.FindControl("ftxtempname");
TextBox ftxtempno = (TextBox)grdview.FooterRow.FindControl("ftxtempno");
TextBox ftxtempemail = (TextBox)grdview.FooterRow.FindControl("ftxtempemail");
TextBox ftxtempage = (TextBox)grdview.FooterRow.FindControl("ftxtempage");
using (con)
{
SqlCommand cmd = new SqlCommand("usp_add_upd_emptb", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpName", ftxtempname.Text);
cmd.Parameters.AddWithValue("#EmpNo", ftxtempno.Text);
cmd.Parameters.AddWithValue("#Desig", ftxtempage.Text);
cmd.Parameters.AddWithValue("#Email", ftxtempemail.Text);
con.Open();
cmd.ExecuteNonQuery();
}
This is a working complete code.

hyperlink in grid view not populating values in another page when clicked

please help with this hyperlink thing.. i got a grid view where one of the column contains hyperlink say ViewDetails. upon clicking ViewDetails it should get navigate to another page called as Reports.aspx where the page should display the grid row value of selectd column in grid view in labels. i have used row data bound event .. im getting blank labels if i click the hyperlink . i have written stored procedure to get the row values. and im calling it through KEY.. its TaskID which is an auto generated column which is invisible. depending on the key value i need to display the row values.
here are the codes
<asp:GridView ID="GrdViewMyTasks" runat="server" AllowSorting="True"
AutoGenerateColumns="False" BackColor="White" BorderColor="#0061C1"
BorderStyle="None" CaptionAlign="Bottom" EmptyDataText="No Records Found"
Font-Names="Verdana" Font-Size="X-Small" ForeColor="#0061C1"
Height="179px" OnRowDataBound="GrdViewMyTasks_RowDataBound"
ShowFooter="True" ShowHeaderWhenEmpty="True" Width="99%"
onselectedindexchanged="GrdViewMyTasks_SelectedIndexChanged"
OnRowCreated="GrdViewMyTasks_RowCreated" >
<Columns>
<asp:BoundField DataField="TaskID" HeaderText="SL No" Visible="False" ReadOnly="True">
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:TemplateField HeaderText="Task Name">
<ItemTemplate>
<asp:Label ID="TaskName" runat="server"
Font-Names="Verdana" Font-Size="X-Small" Height="24px"
Text='<%# Eval("TaskName")%>' Width="70px"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Due Date">
<ItemTemplate>
<asp:Label ID="DueDate" runat="server" Font-Names="Verdana" Font-Size="X-Small"
Height="20px" Width="70px" Text='<%# Eval("DueDate","{0:dd/MM/yyyy}")%>' DataFormatString="{0:dd/MM/yyyy}"></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="Description" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="20px" Width="90px" Text='<%# Eval("Description")%>'></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Assign By">
<ItemTemplate>
<asp:Label ID="AssignBy" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="20px" Width="90px" Text='<%# Eval("AssignBy")%>'></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="Status" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="20px" Width="90px" Text='<%# Eval("Status")%>'></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="% Complete">
<ItemTemplate>
<asp:Label ID="PercentageComplete" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="20px" Width="50px" Text='<%# Eval("PercentageComplete")%>'></asp:Label>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="View Details">
<ItemTemplate>
<asp:HyperLink ID="ViewDetails" runat="server" Font-Names="Verdana" Font-Size="X-Small" Height="24px" Width="70px" ForeColor="#0061C1" Text="ViewDetails" NavigateUrl="Reports.aspx">View</asp:HyperLink>
</ItemTemplate>
<FooterStyle BackColor="#0061C1" />
<HeaderStyle BackColor="#0061C1" ForeColor="White" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
</Columns>
</asp:GridView>
aspx.cs code
protected void GrdViewMyTasks_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink ViewDetails = e.Row.FindControl("ViewDetails") as HyperLink;
ViewDetails.NavigateUrl = "Reports.aspx?TaskID=" + e.Row.Cells[0].Text;
}
}
code in reports.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
MTMSService obj = new MTMSService();
DBAccess db = new DBAccess();
{
MTMSDTO objc = new MTMSDTO();
{
//objc.TaskID = Convert.ToInt32(Request.QueryString["TaskID"]);//
DataSet rep = obj.GetReports();
DataView Rprts = new DataView();
Rprts.Table = rep.Tables[0];
var table = rep.Tables[0];
if (table.Rows.Count > 0)
{
LblTaskID.Text = rep.Tables[0].Rows[0]["TaskID"].ToString();
LblTaskName.Text = rep.Tables[0].Rows[0]["TaskName"].ToString();
LblDueDate.Text = rep.Tables[0].Rows[0]["DueDate"].ToString();
LblDescription.Text = rep.Tables[0].Rows[0]["Description"].ToString();
LblAssignBy.Text = rep.Tables[0].Rows[0]["AssignBy"].ToString();
LblStatus.Text = rep.Tables[0].Rows[0]["Status"].ToString();
LblPercentageComplete.Text = rep.Tables[0].Rows[0]["PercentageComplete"].ToString();
}
else
{
}
LblTaskName.Visible = true;
LblAssignBy.Visible = true;
LblDescription.Visible = true;
LblDueDate.Visible = true;
LblStatus.Visible = true;
LblPercentageComplete.Visible = true;
LblAssignTo.Visible = false;
}
}
}
and this is my stored procedure
ALTER PROCEDURE [dbo].[GetReports]
#TaskID int
AS
Select TaskName, DueDate, Description, AssignBy, Status, PercentageComplete, TaskID
From dbo.Task
Where TaskID = #TaskID;
please let me know where im goin wrong. im unable to get the perfect solution for this from past 1 week... its getting headache thing ..
getting error "input string is not in correct format" at commented line of reports.cs file
You're querying the database with Session["TaskId"] and you're showing task id on UI from query string. Are you sure that both are same?
I think you might want to use taks id from query string rather than session.
objc.TaskID = Convert.ToInt32(Request.QueryString["TaskID"]);
Update -
Filter the table based on your query string
rep.Tables[0].Select(string.Format("TaskID={0}", Request.QueryString["TaskID"]));

retrieve data by clicking on a gridview cell in asp.net using c#

I have a gridview
<asp:GridView ID="wbsdataGV1" runat="server" Width="790px" AutoGenerateColumns="False"
OnSelectedIndexChanged="wbsdataGV1_SelectionChanged" DataKeyNames="WBSCode">
<Columns>
<asp:TemplateField HeaderText="WBS Code">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Eval("WBSCode") %>'></asp:LinkButton>
</ItemTemplate>
<ControlStyle Width="100px" />
<ItemStyle BorderStyle="Solid" BorderWidth="1px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:TextBox ID="TextBox40" runat="server" Text='<%# Eval("Description") %>' ReadOnly="true"
Width="300px">
</asp:TextBox>
</ItemTemplate>
<ControlStyle Width="300px" />
<ItemStyle BorderStyle="Solid" BorderWidth="1px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Territory Code">
<ItemTemplate>
<asp:Label ID="Label45" runat="server" Text='<%# Eval("TerritoryCode") %>'></asp:Label>
</ItemTemplate>
<ControlStyle Width="100px" />
<ItemStyle BorderStyle="Solid" BorderWidth="1px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:Label ID="Label46" runat="server" Text='<%# Eval("AmountReleased") %>'></asp:Label>
</ItemTemplate>
<ControlStyle Width="100px" />
<ItemStyle BorderStyle="Solid" BorderWidth="1px" />
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="Wheat" BorderStyle="Solid" BorderWidth="1px" />
<RowStyle BorderStyle="Solid" BorderWidth="1px" HorizontalAlign="Center"
</asp:GridView>
now in the link button i want to click it and retrieve that row's data in the same page and show it...
i am using
protected void wbsdataGV1_SelectionChanged(object sender, EventArgs e)
{
string rowID = (string)this.wbsdataGV1.SelectedDataKey.Value;
con.Open();
SqlCommand cmd = new SqlCommand(" select WBSCode,Description,TerritoryCode,AmountReleased from WBS where WBSCode='"+rowID+"'");
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
wbssearchdata1.DataSource = dt;
wbssearchdata1.DataBind();
}
con.Close();
}
this code but its not firing on the click .. so how can i solve this.. any help?
From your code I couldn't see anywhere you specified the button that fires the SelectedIndexChanged event. You'll need to do these
<asp:GridView OnSelectedIndexChanged="wbsdataGV1_SelectionChanged"
AutoGenerateSelectButton="true" />
Or
<asp:GridView OnSelectedIndexChanged="wbsdataGV1_SelectionChanged">
<Columns>
<asp:CommandField ShowSelectButton="true" />
</Columns>
</asp:GridView>
Or
<asp:GridView OnSelectedIndexChanged="wbsdataGV1_SelectionChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="Selecting" CommandName="Select" Text="Select Row"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

How can i detect the Link button fire command-button in gridview control

I have a Strange issue that is i have develop a web application in one of the form i am using Gridview control with command button to view the row data.If in Gridview data have only record then link button working fine if it is more than one record not working link buttons i can't under stand, this is very strange issue to me i have use !Page.IsPostBack also in pageload event,please help me .....
protected void grdmanageloans_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Info")
{
try
{
int loanid = Convert.ToInt32(e.CommandArgument);
Session["Loanid"] = loanid;
Session["Edit"] = "Edit";
TabContainer1.ActiveTabIndex = 1;
Session["TabContainer1"] ="loantab";
Session["Tabloan"] = "Tabloan";
Response.Redirect("Mortgageclient.aspx");
}
catch { }
}
if (e.CommandName == "Delete")
{
try
{
int LoanId = Convert.ToInt32(e.CommandArgument);
var PmtScheduleHistory = from del in mortgageentity.Pmt_Schedule_History where del.Loan.Loan_ID == LoanId select del;
var LoanPayment = from del in mortgageentity.Payments where del.Loan_ID == LoanId select del;
if (PmtScheduleHistory.Count() > 0)
{
var DelPmtScheduleHistory = (from del in mortgageentity.Pmt_Schedule_History where del.Loan.Loan_ID == LoanId select del).First();
mortgageentity.DeleteObject(DelPmtScheduleHistory);
mortgageentity.SaveChanges();
}
var Getpayments = from db in mortgageentity.Payments where db.Loan_ID == LoanId select db;
if (Getpayments.Count() > 0)
{
foreach (var i in Getpayments)
{
mortgageentity.DeleteObject(i);
mortgageentity.SaveChanges();
}
}
if (LoanPayment.Count() > 0)
{
var DelPmtScheduleHistory = (from del in mortgageentity.Payments where del.Loan_ID == LoanId select del.Payment_Status.PaymentStatus_ID).First();
mortgageentity.DeleteObject(DelPmtScheduleHistory);
mortgageentity.SaveChanges();
}
var deletedata = (from del in mortgageentity.Loans where del.Loan_ID == LoanId select del).First();
mortgageentity.DeleteObject(deletedata);
mortgageentity.SaveChanges();
BindData();
}
catch { }
}
if (e.CommandName == "AddNewloan")
{
Session["Addnewloan"] = "Addloan";
Response.Redirect("Information.aspx");
}
}
Here is my .aspx page
<asp:GridView ID="grdmanageloans" runat="server" AutoGenerateColumns="False" AllowSorting="True"
GridLines="Both" PageSize="10" AllowPaging="true" OnRowCommand="grdmanageloans_RowCommand"
OnSelectedIndexChanged="grdmanageloans_SelectedIndexChanged" ShowFooter="true"
OnPageIndexChanging="grdmanageloans_PageIndexChanging" OnRowDataBound="grdmanageloans_Rowdatabound">
<AlternatingRowStyle BackColor="#F3F9FB" />
<RowStyle BackColor="#FEFEFE" VerticalAlign="Top" />
<HeaderStyle BackColor="#F3F9FB" />
<FooterStyle BackColor="#F3F9FB" />
<RowStyle Wrap="False" />
<HeaderStyle ForeColor="#1F476F" />
<Columns>
<asp:TemplateField HeaderText="LoanID" Visible="true">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="lblloanid" runat="server" Text='<%# Bind("Loan_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Loan Number">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="lblLoanNumber" runat="server" Text='<%# Bind("LoanNumber") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Month Pay Amt" HeaderStyle-Wrap="false">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="lblMonthPayAmt" runat="server" Text='<%#Getammount(Eval("MonthPayAmt","{0:F2}")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="lblpropaddress" runat="server" Text='<%# Bind("PropAddress") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="lblpropcity" runat="server" Text='<%# Bind("PropCity") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="State">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="lblpropstate" runat="server" Text='<%# Bind("PropState") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ClientID" Visible="false">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="lblclientid" runat="server" Text='<%# Bind("Client_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:LinkButton ID="lnkeinfo" runat="server" CausesValidation="false" CommandName="Info"
CommandArgument='<%#Eval("Loan_ID")%>'>Information</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Try this:
<asp:LinkButton ID="lnkeinfo" runat="server" CausesValidation="false" CommandName="Info"
CommandArgument='<%# Bind("Loan_ID") %>'>Information</asp:LinkButton>
Why don't you use a RESTful architecture to not save those parameters in Session and make pages kind'ev tightly coupled? Just create links named Info in your Grid instead of buttons (which post back data) with those parameters appended to the end of them as querystring. This is nicer approach and the result is the same.

ASP.NET Gridview RowUpdating event not firing

HTML Page:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:GridView ID="Grd_Threshold" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="Both" AutoGenerateColumns="false" EmptyDataText="No Records." PageSize="8"
AllowPaging="true" OnPageIndexChanging="Grd_Threshold_PageIndexChanging" OnRowCommand="Grd_Threshold_RowCommand"
DataKeyNames="ID" AutoGenerateEditButton="true" OnRowCancelingEdit="Grd_Threshold_RowCancelingEdit" OnRowEditing="Grd_Threshold_RowEditing"
OnRowUpdating="Grd_Threshold_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="No.">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="150px">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("CLNAME") + ", " + Eval("CFNAME") +" " +Eval("CMNAME")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Doctor" ItemStyle-Width="150px">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("DOCTORNAME")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Name" ItemStyle-Width="150px">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("INAME")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Form" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("IFORM")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Strength" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ISTRG")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Order Date" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ORDERDATE")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" ItemStyle-Width="80px">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("PRICE")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity" ItemStyle-Width="80px">
<EditItemTemplate>
<asp:TextBox ID="Txt_Qty" runat="server" Width="50px" Text='<%# Eval("QTY")%>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("QTY")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("USERID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#E3EAEB" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#7C6F57" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
CS Code:
protected void Page_Load(object sender, EventArgs e)
{
try
{
Title = "Dashboard";
if (!Master.Page.IsPostBackEventControlRegistered)
{
BindGrid();
}
}
catch (Exception ex)
{
Common.WriteLog(ex);
}
}
private void BindGrid()
{
try
{
if (SessionUtility.DashboardRecords == null || SessionUtility.DashboardRecords.Rows.Count == 0)
{
string WebServiceUrl = SessionUtility.WebServiceUrl + "/GetAllOrders/";
JsonArrayCollection ReqResponse = Common.GetWebServiceResponse_MultipleValues(WebServiceUrl, "GET");
DataTable Patients = Common.ConvertJsonArrayObjectCollectionToDataTable(ReqResponse);
SessionUtility.DashboardRecords = Patients;
}
if (SessionUtility.UserRight != "1")
{
//Grd_Threshold.Columns[0].Visible = false;
Grd_Threshold.AutoGenerateEditButton = false;
}
else if (SessionUtility.UserRight == "1")
{
Grd_Threshold.AutoGenerateEditButton = true;
}
Grd_Threshold.DataSource = SessionUtility.DashboardRecords;
Grd_Threshold.DataBind();
UpdatePanel1.Update();
}
catch (Exception ex)
{
Common.WriteLog(ex);
}
}
Hi All,
In above written code only EDIT event is being fired & that is only once after that UPDATE,CANCEL no event is being fired. What am i doing wrong?All I want to do is change the GridRow Color on the basis of the value entered in QTY field.
I figured out the problem. The event was not firing because of the same IDs that i had given to the Label in each row. Hope this helpful to someone.
Not sure about your use of IsPostBackEventControlRegistered - I havent seen it used before but it seems that probably you are wiping out your update event by DataBind() every time in Page_Load().
Page_Load is fired every time the page loads which is then changing what the page is doing by resetting the grid.
Try wrapping the control in:
if(!IsPostBack)
{
// bind
}
so that it only does this on the first page load.

Categories

Resources