Find control in grid view control - c#

I know there are alot of questions&answers about this but non of them works for me
Trying to populate this Drop Down List via a function in code behind:
This drop down list is for Images names, when a user choose one and clicks the "Update" link button in the Grid View I need to insert a suffix to the image name (for the path),
so if the user choose an image name from the list the update button it will actually update the fileName + insert at the beginning the path, so it would be
../images/gary.jpg
for the name gary.
aspx page
<asp:TemplateField>
<EditItemTemplate>
<asp:DropDownList ID="ddlImages" runat="server">
<Items>
<asp:ListItem Text="Choose" Value="" />
</Items>
</asp:DropDownList>
</EditItemTemplate>
...
code behind
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlImages = (e.Row.FindControl("ddlImages") as DropDownList);
ShowImages(ddlImages);
}
}
"ddlImages" is null, how can I find him?
Managed to find the drop down list like that:
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlImages = (DropDownList)e.Row.FindControl("ddlImages");
ddlImages.DataSource = GetImages();
ddlImages.DataBind();
}
}
Now i am facing another problem, in the aspx i have an "UpdateCommand" which take parameters and try to update the database. The problem- it need to take the dropDownList chosen value but instead it take: "" how can i change it to take the value that the user choose in the dropDownList
aspx page
UpdateCommand="UPDATE [investigator] SET [name] = #name, [area] = #area, [country] = #country, [picture] = #picture, [review] = #review WHERE [Id] = #Id">
<UpdateParameters>
<asp:Parameter Name="name" Type="String" />
<asp:Parameter Name="area" Type="String" />
<asp:Parameter Name="country" Type="String" />
<asp:Parameter Name="picture" Type="String" />
<asp:Parameter Name="review" Type="String" />
<asp:Parameter Name="Id" Type="Int32" />
</UpdateParameters>
Meaning- I have to change
<asp:Parameter Name="picture" Type="String" />
to drop down list selected value. How can I achieve that?

Regarding your question about the update Parameter, you should use the ControlParameter instead of general Parameter. Try replacing the Parameter Definition for the Dropdown list with following
code.
<asp:ControlParameter Name="picture" ControlID="ddlImages"
PropertyName="SelectedValue" Type="String" />
UPDATE
What you can do as alternate is,
Change the parameter back to
<asp:Parameter Name="picture" Type="String" />
Add RowUpdating event handler to the gridview
In the RowUpdating command set the data source parameter based on the selected value as below
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
DropDownList ddlImages= row.FindControl("ddlImages") as DropDownList;
SqlDataSource1.UpdateParameters["picture"].DefaultValue = ddlImages.SelectedValue;
}

Related

Receiving error in Datasource when attempting insert command

I am getting the following error message when attempting the InsertCommand of the datasource:
Procedure or function 'student_insert' expects parameter '#password', which was not supplied.
I have most of the parameters set up in the ASCX page, except for 'password', since I need to do some manipulation to it before saving it in the DB:
<InsertParameters>
<asp:Parameter Name="email" Type="String" />
<asp:Parameter Name="first_name" Type="String" />
<asp:Parameter Name="last_name" Type="String" />
<asp:Parameter Name="university" Type="String" />
<asp:Parameter Name="program" Type="String" />
<asp:Parameter Name="student_number" Type="String" />
<asp:ControlParameter Name="graduation_date" Type="DateTime" ControlID="ctl00$ContentPlaceHolder$ctl01$frmStudents$txtGradDate" PropertyName="Text" />
<asp:ControlParameter Name="student_card_image_name" Type="String" ControlID="ctl00$ContentPlaceHolder$ctl01$frmStudents$FUStudent" PropertyName="FileName" />
<asp:ControlParameter Name="id_card_image_name" Type="String" ControlID="ctl00$ContentPlaceHolder$ctl01$frmStudents$FUID" PropertyName="FileName" />
</InsertParameters>
C#:
protected void datasource_Inserting(object sender, SqlDataSourceCommandEventArgs e) {
ASCIIEncoding encoding = new ASCIIEncoding();
ControlParameter cp = new ControlParameter("#password", DbType.Binary, "ctl00$ContentPlaceHolder$ctl01$frmStudents$txtPassword", "Text");
FormView frmStudents = (FormView)FindControl("frmStudents");
TextBox txtPassword = (TextBox)(frmStudents.FindControl("txtPassword"));
datasource.InsertParameters.Add("password", DbType.Binary, encoding.GetBytes(Cryptogrpahy.Encrypt(txtPassword.Text, basepage.crypt_password)).ToString());
}
When I go through the method with the debugger, I see my entire InsertParameters, with values...
Also, on a side note, not sure this will execute successfully due to the DB Type, as I usually use VarBinary in regular SQLParamater.
I can't find documentation on it, but I suspect what is happening is that the SqlCommand object that gets created during the Insert event is getting its parameters from the state of the SqlDataSource.InsertParameters object BEFORE your event handler code executes. You're adding the parameter to the SqlDataSource, but since the SqlCommand was created and received its parameters from the SqlDataSource instance before you added the parameter to the SqlDataSource instance the SqlCommand never gets the password parameter.
To get around this try adding the password parameter to e.Command.Parameters in your event handler instead of to datasource.
protected void datasource_Inserting(object sender, SqlDataSourceCommandEventArgs e) {
ASCIIEncoding encoding = new ASCIIEncoding();
ControlParameter cp = new ControlParameter("#password", DbType.Binary, "ctl00$ContentPlaceHolder$ctl01$frmStudents$txtPassword", "Text");
FormView frmStudents = (FormView)FindControl("frmStudents");
TextBox txtPassword = (TextBox)(frmStudents.FindControl("txtPassword"));
e.Command.Parameters.Add("password", DbType.Binary, encoding.GetBytes(Cryptogrpahy.Encrypt(txtPassword.Text, basepage.crypt_password)).ToString());
}

Make a DropDownList inside a GridView with Object Data Source

I have make a gridview with object data source. I make a class for the Object Data Source and make the gridview in aspx page.
It was run perfectly, but i want to make, when i update the table, there is two coloumn that will turn into dropdownlist, not free text.
I dont know how to make that, can you make/give me some example.
This is my Object Data Source Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace quittance.Kelas
{
public class dalamkota_rincian_8:daftarproperti
{
public static List<daftarproperti> AmbilJadwal(string nomorSt)
{
List<daftarproperti> Listjadwal = new List<daftarproperti>();
string CS = ConfigurationManager.ConnectionStrings["nikita_app"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("xp_generatejadwal_dalamkota8", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramnoSt = new SqlParameter("#nomorSt", nomorSt);
cmd.Parameters.Add(paramnoSt);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
daftarproperti jadwal = new daftarproperti();
jadwal.tugasID = (int)rdr["tugasID"];
jadwal.nama = rdr["nama"].ToString();
jadwal.nip = rdr["nip"].ToString();
jadwal.gol = rdr["gol"].ToString();
jadwal.tgl_mulai = rdr["tgl_mulai"].ToString();
jadwal.tgl_selesai = rdr["tgl_selesai"].ToString();
jadwal.jumlahhari1 = rdr["jumlahhari1"] as int? ?? default(int);
Listjadwal.Add(jadwal);
}
}
return Listjadwal;
}
}
}
The Object Data Source and the Gridview has been connected.
<asp:ObjectDataSource ID="ds_dalamkota8_jadwal" runat="server" DeleteMethod="DeleteJadwal" InsertMethod="InsertJadwal" SelectMethod="AmbilJadwal" TypeName="quittance.Kelas.dalamkota_rincian_8" UpdateMethod="UpdateJadwal">
<DeleteParameters>
<asp:Parameter Name="tugasID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="nip" Type="String" />
<asp:Parameter Name="gol" Type="String" />
<asp:Parameter Name="kdlokasi" Type="Int32" />
<asp:Parameter Name="tgl_mulai" Type="String" />
<asp:Parameter Name="tgl_selesai" Type="String" />
</InsertParameters>
<SelectParameters>
<asp:SessionParameter Name="nomorSt" SessionField="nomorst" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="tugasID" Type="Int32" />
<asp:Parameter Name="nip" Type="String" />
<asp:Parameter Name="gol" Type="String" />
<asp:Parameter Name="kdlokasi" Type="Int32" />
<asp:Parameter Name="tgl_mulai" Type="String" />
<asp:Parameter Name="tgl_selesai" Type="String" />
</UpdateParameters>
</asp:ObjectDataSource>
I want to make the nip and gol coloumn turn into dropdownlist when i edit that. I dont know how to make it with object data source, should i make in Object Data Source class or in aspx.cs page with sqldatasource.
Please give me an example/explanation.
you can call the method one which provide data from the page load event then you a can bind data to drop down
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = AmbilJadwal(nomorSt);
GridView1.DataBind();
}
}
Help link is given below most likely it will solve your problem
Bind DropDownList in ItemTemplate of TemplateField in ASP.Net GridView

Getting QueryStringParameter value for InsertParameter in C# codebehind

I am dealing with a gridview in an ASP.NET Web Form that is using a QueryStringParameter as its Select Parameter. As I am having to do the Insert for the GridView in code-behind, I am trying to find an example of how I get the value of the QueryStringParameter for my SQLDataSource.InsertParameters.Add() chunk and I am coming up blank.
SQL DataSource:
<asp:SqlDataSource ID="gvProjectTaskSQL" runat="server" ConnectionString="<%$ ConnectionStrings:SQLConnectionString %>"
SelectCommand="SELECT tt.TaskID,
tt.EmployeeID,
tt.ProjectID,
tt.ReleaseID,
tt.TaskStatusID,
tt.TaskPriorityID,
tt.DueDate,
tt.Notes,
tt.CompDate,
p.ProjectName,
tc.TaskCodeAbbr
FROM tblTaskTracker tt INNER JOIN
tblProject p ON tt.ProjectID = p.ProjectID INNER JOIN
tblTaskCode tc ON tt.TaskCodeID = tc.TaskCodeID INNER JOIN
tblTaskStatus ts on tt.TaskStatusID = ts.TaskStatusID
WHERE tt.ProjectID = #ProjectID AND ts.TaskStatusType <> 'Z'
ORDER BY ts.TaskStatusType, tt.TaskPriorityID, tt.DueDate"
InsertCommand="INSERT INTO [tblTaskTracker]
([EmployeeID], [ProjectID], [ReleaseID], [TaskCodeID], [TaskStatusID], [TaskPriorityID], [DueDate], [Notes], [CompDate])
VALUES (#EmployeeID, #ProjectID, #ReleaseID, #TaskCodeID, #TaskStatusID, #TaskPriorityID, #DueDate, #Notes, #CompDate)"
UpdateCommand="UPDATE [tblTaskTracker] SET [EmployeeID] = #EmployeeID, [TaskStatusID] = #TaskStatusID, [TaskPriorityID] = #TaskPriorityID,
[DueDate] = #DueDate, [Notes] = #Notes, [CompDate] = #CompDate WHERE [TaskID] = #TaskID"
DeleteCommand="DELETE FROM [tblTaskTracker] WHERE [TaskID] = #TaskID">
<SelectParameters>
<asp:QueryStringParameter Name="ProjectID" Type="Int32" QueryStringField="PID" />
</SelectParameters>
<InsertParameters>
<asp:Parameter Name="EmployeeID" Type="Int32" />
<asp:Parameter Name="ProjectID" Type="Int32" />
<asp:Parameter Name="ReleaseID" Type="Int32" />
<asp:Parameter Name="TaskCodeID" Type="Int32" />
<asp:Parameter Name="TaskStatusID" Type="Int32" />
<asp:Parameter Name="TaskPriorityID" Type="Int32" />
<asp:Parameter Name="DueDate" Type="DateTime" />
<asp:Parameter Name="Notes" Type="String" />
<asp:Parameter Name="CompDate" Type="DateTime" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="EmployeeID" Type="Int32" />
<asp:Parameter Name="TaskID" Type="Int32" />
<asp:Parameter Name="TaskStatusID" Type="Int32" />
<asp:Parameter Name="TaskPriorityID" Type="Int32" />
<asp:Parameter Name="DueDate" Type="DateTime" />
<asp:Parameter Name="Notes" Type="String" />
<asp:Parameter Name="CompDate" Type="DateTime" />
</UpdateParameters>
<DeleteParameters>
<asp:Parameter Name="TaskID" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
Codebehind for OnRowCommand:
protected void gvProjectTask_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "FooterInsert" && Page.IsValid)
{
GridView gv = (GridView)MultiView1.Views[10].FindControl("gvProjectTask");
GridViewRow gvr = (GridViewRow)gv.FooterRow;
if (gvr == null) { return; }
// Get Controls
DropDownList ddlEmployee = gvr.FindControl("ddlNewEmployee") as DropDownList;
TextBox txtReleaseID = gvr.FindControl("txtNewReleaseID") as TextBox;
DropDownList ddlTaskCode = gvr.FindControl("ddlNewTaskCode") as DropDownList;
DropDownList ddlStatus = gvr.FindControl("ddlNewStatus") as DropDownList;
DropDownList ddlPriority = gvr.FindControl("ddlNewPriority") as DropDownList;
TextBox txtDueDate = gvr.FindControl("txtNewDueDate") as TextBox;
TextBox txtNotes = gvr.FindControl("txtNewNotes") as TextBox;
TextBox txtCompDate = gvr.FindControl("txtNewCompDate") as TextBox;
// Test for nulls
if (string.IsNullOrWhiteSpace(txtDueDate.Text))
{
// Throw error message
ClientScript.RegisterStartupScript(GetType(), "error", "alert('Enter Due Date.');", true);
}
else
{
// Initialize Insert Parameters
gvProjectTaskSQL.InsertParameters.Clear();
gvProjectTaskSQL.InsertParameters.Add("EmployeeID", ddlEmployee.SelectedValue);
// gvProjectTaskSQL.InsertParameters.Add("ProjectID", gvProjectTaskSQL.SelectParameters.ToString());
gvProjectTaskSQL.InsertParameters.Add("ReleaseID", txtReleaseID.Text);
gvProjectTaskSQL.InsertParameters.Add("TaskCodeID", ddlTaskCode.SelectedValue);
gvProjectTaskSQL.InsertParameters.Add("TaskStatusID", ddlStatus.SelectedValue);
gvProjectTaskSQL.InsertParameters.Add("TaskPriorityID", ddlPriority.SelectedValue);
gvProjectTaskSQL.InsertParameters.Add("DueDate", txtDueDate.Text);
gvProjectTaskSQL.InsertParameters.Add("Notes", txtNotes.Text);
gvProjectTaskSQL.InsertParameters.Add("CompDate", txtCompDate.Text);
gvProjectTaskSQL.Insert();
}
} // end FooterInsert
if (e.CommandName == "EmptyInsert" && Page.IsValid)
{
GridView gv = (GridView)MultiView1.Views[10].FindControl("gvProjectTask");
GridViewRow gvr = (GridViewRow)gv.Controls[0].Controls[0];
if (gvr == null) { return; }
// Get Controls
DropDownList ddlEmployee = (DropDownList)gvr.FindControl("ddlEmptyEmployee");
TextBox txtReleaseID = (TextBox)gvr.FindControl("txtEmptyReleaseID");
DropDownList ddlTaskCode = (DropDownList)gvr.FindControl("ddlEmptyTaskCode");
DropDownList ddlStatus = (DropDownList)gvr.FindControl("ddlEmptyStatus");
DropDownList ddlPriority = (DropDownList)gvr.FindControl("ddlEmptyPriority");
TextBox txtDueDate = (TextBox)gvr.FindControl("txtEmptyDueDate");
TextBox txtNotes = (TextBox)gvr.FindControl("txtEmptyNotes");
TextBox txtCompDate = (TextBox)gvr.FindControl("txtEmptyCompDate");
// Test for nulls
if (string.IsNullOrWhiteSpace(txtDueDate.Text))
{
// Throw error message
ClientScript.RegisterStartupScript(GetType(), "error", "alert('Enter Due Date.');", true);
}
else
{
// Initialize Insert Parameters
gvProjectTaskSQL.InsertParameters.Clear();
gvProjectTaskSQL.InsertParameters.Add("EmployeeID", ddlEmployee.SelectedValue);
// gvProjectTaskSQL.InsertParameters.Add("ProjectID", gvProjectTaskSQL.SelectParameters.ToString());
gvProjectTaskSQL.InsertParameters.Add("ReleaseID", txtReleaseID.Text);
gvProjectTaskSQL.InsertParameters.Add("TaskCodeID", ddlTaskCode.SelectedValue);
gvProjectTaskSQL.InsertParameters.Add("TaskStatusID", ddlStatus.SelectedValue);
gvProjectTaskSQL.InsertParameters.Add("TaskPriorityID", ddlPriority.SelectedValue);
gvProjectTaskSQL.InsertParameters.Add("DueDate", txtDueDate.Text);
gvProjectTaskSQL.InsertParameters.Add("Notes", txtNotes.Text);
gvProjectTaskSQL.InsertParameters.Add("CompDate", txtCompDate.Text);
gvProjectTaskSQL.Insert();
}
} // end EmptyInsert
} // end gvTask_Command
I've commented out the InsertParameter for the ProjectID as I am sure it's incorrect. I just can't find any examples of how to pass a QueryString value to an InsertParameter.
Just add this code to you OnRowCommand event to get the query string value:
string projectID = Request.QueryString["PID"];

Get ID in insert command asp and use it in code behind c#

I have a listview
<asp:ListView ID="ListViewNews" runat="server" DataSourceID="SqlDataSourceAddNews" DataKeyNames="Id" InsertItemPosition="LastItem" OnItemCommand="ListViewNews_ItemCommand">
<InsertItemTemplate>
<asp:FileUpload ID="FileUpload2" runat="server" />
</InsertItemTemplate>
and the sqldatasource:
<asp:SqlDataSource runat="server" ID="SqlDataSourceAddNews"
ConnectionString='<%$ ConnectionStrings:ConnectionStringSchool %>'
DeleteCommand="DELETE FROM [News] WHERE [Id] = #Id"
InsertCommand="INSERT INTO News(TITLE, SUMMARY, TEXT, DATETIME, PHOTO, [FILE])
VALUES (#TITLE, #SUMMARY, #TEXT, #DATETIME, #PHOTO, #FILE)"
SelectCommand="SELECT * FROM [News] ORDER BY DATETIME DESC">
<DeleteParameters>
<asp:Parameter Name="Id" Type="Int32"></asp:Parameter>
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="TITLE" Type="String"></asp:Parameter>
<asp:Parameter Name="SUMMARY" Type="String"></asp:Parameter>
<asp:Parameter Name="TEXT" Type="String"></asp:Parameter>
<asp:Parameter Name="DATETIME" Type="DateTime"></asp:Parameter>
<asp:Parameter Name="PHOTO" Type="String"></asp:Parameter>
<asp:Parameter Name="FILE" Type="String"></asp:Parameter>
</InsertParameters>
</asp:SqlDataSource>
I want to get the id of insert command to name the uploaded photo
protected void ListViewNews_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
string strID= ....get id here....;
FileUpload fu2 = (FileUpload)ListViewNews.InsertItem.FindControl("FileUpload2");
if (fu2.HasFile)
{
string aut = strID + ".jpg";
fu2.SaveAs(Server.MapPath("~/images/NewsPhotos/" + aut));
}
}
}
Any idea for a simple solution how to get the id here?
Try this,
Change your insert command to:
InsertCommand="INSERT INTO News(TITLE, SUMMARY, TEXT, DATETIME, PHOTO, [FILE])
VALUES (#TITLE, #SUMMARY, #TEXT, #DATETIME, #PHOTO, #FILE);
SELECT #Id = SCOPE_IDENTITY();"
Add New Output Parameter to InsertParameters List
<asp:Paramter Direction="Output" Name="Id" Type="Int32" />
Move your file saving code to SQLDataSource Inserted method, you cannot access this generated id in ItemCommand Event directly
protected void SqlDataSourceAddNews_Inserted(object sender, EventArgs e)
{
string strId = e.Command>parameters("#Id").Value.ToString();
FileUpload fu2 = (FileUpload)ListViewNews.InsertItem.FindControl("FileUpload2");
if (fu2.HasFile)
{
string aut = strID + ".jpg";
fu2.SaveAs(Server.MapPath("~/images/NewsPhotos/" + aut));
}
}

Customize SqlDataSource to store part of string

I'm using an UpdatePanel in ASP.Net WebForms to upload a image. I set the Image.ImageUrl to the full virtual path to the image (/images/news/filenname.jpg), but I only want to save the filename in the database (filename.jpg). How do I customize the SqlDataSource to only take part of the URL?
<asp:SqlDataSource
ID="SqlDataSourceNews"
runat="server"
ConnectionString="<%$ ConnectionStrings:connectionString %>"
UpdateCommand="UPDATE [foo] SET [pic] = #pic WHERE [id] = #id">
<UpdateParameters>
<asp:Parameter Name="pic" Type="String" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="pic" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
You can set the update parameters on page_load and use substring function to get only file name from full url:
protected void Buton_Click(object sender, EventArgs e)
{
SqlDataSource1.UpdateParameters["pic"].DefaultValue = "string fetched from substring method";
SqlDataSource1.Update();
}

Categories