Cannot get textbox value from textbox in itemtemplate - c#

The quantity (quantityWanted in DB) in textbox is loaded via Eval() method from Basket DB table. What I want to achieve is that when I change quantity manually and click update the quantity for that record will be updated and then grid will be reloaded. I seem unable to retrieve value of that textbox in code behind.
I am aware of FindControl() method which is used to get value from controls within itemtemplate but I don't know how to use it here.
The tried below but always get nullReferenceException
TextBox txt = (TextBox)GridView2.FindControl("txtQuantityWanted");
int _quantity = Convert.ToInt16(txt.Text);
Note: button is there but does nothing.
<ItemTemplate>
<asp:TextBox runat="server" ID="txtQuantityWanted" Text='<%# Eval("quantityWanted") %>' ></asp:TextBox>
<asp:LinkButton ID="LinkButton11" runat="server" CommandName="update" CommandArgument='<%# Eval("coffeeName") + ";" + Eval("datetimeAdded") %>' >Update</asp:LinkButton>
<asp:Button ID="Button21" runat="server" Text="Button" CommandName="edit" />
</ItemTemplate>
<asp:TemplateField HeaderText="Total [£]">
<ItemTemplate>
<asp:Label id="lblItemTotal" runat="server" Text='<%# String.Format("{0:C}", Convert.ToInt32(Eval("quantityWanted"))* Convert.ToDouble(Eval("price"))) %>' ></asp:Label>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="remove" CommandArgument='<%# Eval("coffeeName") + ";" + Eval("datetimeAdded") %>' >Remove</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
C# code:
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
// .....
else if (e.CommandName == "update")
{
string params = Convert.ToString(e.CommandArgument);
string[] arg = new string[2];
arg = params.Split(';');
name = Convert.ToString(arg[0]);
datetimeAdded = Convert.ToString(arg[1]);
const string strConn = #"Data Source=.\SQLEXPRESS;AttachDbFilename=L:\ASP.NET\Exercise1\Exercise1\Exercise1\App_Data\ASPNETDB.MDF;Integrated Security=True;Connect Timeout=30;User Instance=True";
DataSet ds = new DataSet("Employees");
SqlConnection connection = new SqlConnection(strConn);
// Here I need value from textbox to replace 11
SqlCommand abc = new SqlCommand("UPDATE Basket SET quantityWanted = 11 WHERE coffeeName LIKE '%" + name + "%' AND datetimeAdded LIKE '" + datetimeAdded + "' ", connection);
connection.Open();
int ii = abc.ExecuteNonQuery();
connection.Close();
}
}

Use GridView.Rows collection to find control. You can pass the index of row in rows collection indexer.
TextBox txt = (TextBox)GridView2.Rows[0].FindControl("txtQuantityWanted");

You must pass the row index as well,Your code will look like this
TextBox txt = (TextBox)GridView2.Rows[0].FindControl("txtQuantityWanted");
I hope it will work for you.

Control ctrl = e.CommandSource as Control;
if (ctrl != null)
{
GridViewRow gvRow = ctrl.Parent.NamingContainer as GridViewRow;
TextBox txt= (TextBox)gvRow.FindControl("txtQuantityWanted");
}

Related

How to insert image from gridview to another table in database

Dear all I am displaying an image in my gridview, this image is saved in database in varbinary format, with its content type and image name. And my image in gridview is displaying perfect, now I want to insert this same image from gridview to another table from the button click outside the gridview, How do I achieve this can anyone please guide me? I tried achieving it by receiving this image data from gridview such as Varbinary data - which is an image in database and content type and imagename into textbox but it thorws an error "Implicit conversion from data type nvarchar to varbinary(max) is not allowed. Use the CONVERT function to run this query"
<asp:TemplateField HeaderText="" ItemStyle-Width="" Visible="true">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" class="preview" ToolTip='<%#Bind("StaffName") %>'
NavigateUrl='' runat="server">
<asp:ImageButton runat="server" ID="Image2" class="img2" ImageUrl='<%# Eval("ImageName") %>'
CommandName='<%# Eval("Id") %>' CommandArgument='<%# Eval("ImageName") %>' />
</asp:HyperLink>
<asp:TextBox ID="txtFileType" runat="server" Text='<%# Eval("FileType") %>' Visible="true"></asp:TextBox>
<asp:TextBox ID="txtBData" runat="server" Text='<%# Eval("BData") %>' Visible="true"></asp:TextBox>
<asp:TextBox ID="txtImageName" runat="server" Text='<%# Eval("ImageName") %>' Visible="true"></asp:TextBox>
<br />
<br />
</ItemTemplate>
<ControlStyle Width="100%" />
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="10%" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="20%" />
</asp:TemplateField>
foreach (GridViewRow row1 in gvImage.Rows)
{
if (row1.RowType == DataControlRowType.DataRow)
{
// txtFileType
// txtBData
// txtImageName
TextBox txtFileType, txtBData, txtImageName;
txtFileType = (row1.Cells[1].FindControl("txtFileType") as TextBox);
txtBData = (row1.Cells[1].FindControl("txtBData") as TextBox);
txtImageName = (row1.Cells[1].FindControl("txtImageName") as TextBox);
string constr = ConfigurationManager.ConnectionStrings["CONNECTION"].ConnectionString;
using (SqlConnection con8 = new SqlConnection(constr))
{
string query = "insert into SShare (FId,UDetails,ShareBy,ShareByUserId,BData,FileType,ImageName) values(#FId,#UDetails,#ShareBy,#ShareByUserId,#BData,#FileType,#ImageName)";
using (SqlCommand cmd8 = new SqlCommand(query))
{
cmd8.Parameters.AddWithValue("#FId", txt_Tester.Text);
cmd8.Parameters.AddWithValue("#UDetails", TextBox1.Text);
cmd8.Parameters.AddWithValue("#ShareBy", txt_StaffId.Text);
cmd8.Parameters.AddWithValue("#ShareByUserId", txt_Employee.Text);
cmd8.Parameters.AddWithValue("#BData", txtBData.Text);
cmd8.Parameters.AddWithValue("#FileType", txtFileType.Text);
cmd8.Parameters.AddWithValue("#ImageName", txtImageName.Text);
con8.Open();
// cmd8.ExecuteNonQuery();
this.ExecuteQuery(cmd8, "SELECT");
con8.Close();
}
}
}
}
Here is what I suggest. You could get all the data out of the grid, but you can also just do it in SQL.
Notice BDAta is NOT a SqlParameter, it is pulled from the Employee table:
INSERT INTO [SShare](FId,UDetails,ShareBy,ShareByUserId,BData,FileType,ImageName)
SELECT #FId, #UDetails, #ShareBy, #ShareByUserId, BData, #FileType, #ImageName
FROM Employee
WHERE FId = #FId;
After beating head everywhere atlast I figured out and I am posting it incase if someone may refer to. Thanks to #Crowcoder for giving a logic to make it happen.
foreach (GridViewRow row1 in gvImage.Rows)
{
if (row1.RowType == DataControlRowType.DataRow)
{
string Id = gvImage.DataKeys[row1.RowIndex].Value.ToString();
ImageButton imgbtn = (ImageButton)gvImage.Rows[row1.RowIndex].FindControl("Image2");
string filename = imgbtn.ImageUrl;
TextBox ftype = (row1.FindControl("txtFileType") as TextBox);
byte[] bytes = (byte[])GetData("SELECT BData FROM Employee WHERE Id =" + txt_StaffId.Text).Rows[0]["BData"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
imgbtn.ImageUrl = "data:image/png;base64," + base64String;
{
string constr = ConfigurationManager.ConnectionStrings["CONNECTION"].ConnectionString;
using (SqlConnection con8 = new SqlConnection(constr))
{
string query = "insert into SShare (FId,UDetails,ShareBy,ShareByUserId,BData,ImageName, FileType) values(#FId,#UDetails,#ShareBy,#ShareByUserId,#BData,#ImageName,#FileType)";
using (SqlCommand cmd8 = new SqlCommand(query))
{
cmd8.Parameters.AddWithValue("#FId", txt_Tester.Text);
cmd8.Parameters.AddWithValue("#UDetails", TextBox1.Text);
cmd8.Parameters.AddWithValue("#ShareBy", txt_StaffId.Text);
cmd8.Parameters.AddWithValue("#ShareByUserId", txt_Employee.Text);
cmd8.Parameters.AddWithValue("#BData", bytes);
cmd8.Parameters.AddWithValue("#ImageName", filename);
cmd8.Parameters.AddWithValue("#FileType", ftype.Text);
con8.Open();
// cmd8.ExecuteNonQuery();
this.ExecuteQuery(cmd8, "SELECT");
con8.Close();
}
}
}
}
}

How to open a link in a new tab using ASP Link Button Property?

I have a gridview with the Template and it contains a LinkButton. When I click the button I want to open a link in new tab
<Templates>
<Obout:GridTemplate runat="server" ID="tempCurrTask">
<Template>
<asp:LinkButton Text='<%# Container.DataItem["CurrentTask"] %>' ID="lnkbtnview2"
runat="server" Font-Underline="true" OnCommand="SELREC" CommandArgument='<%# Container.PageRecordIndex %>'></asp:LinkButton>
</Template>
</Obout:GridTemplate>
And the SELREC function is
protected void SELREC(object sender, CommandEventArgs e)
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
Hashtable dataItem = grvLeads.Rows[rowIndex].ToHashtable() as Hashtable;
string id = Convert.ToString(dataItem["iTask_id"]); //.Split('|');
string rowIndexid = id.ToString();
//+ "/" + e.CommandName.ToString();
//ScriptManager.RegisterStartupScript(this, typeof(string), "openWindow", "window.open('Task.aspx?TaskID=" + rowIndexid.Trim() + "', '_newtab','left = 10, top=10,scrollbars=Yes,resizable=yes,width=1100,height=580'); ", true);
Response.Redirect("Task.aspx?TaskID=" + rowIndexid.Trim());
}
This link opens in the same tab. I want it to open in new tab, So I changed the asp:LinkButton to asp:HyperLink tag but the SELREC function is not called properly. I want to do it using LinkButton and I don't know how to do it by using the link button. So please anybody help me with sample code.
Try this approach;
<asp:LinkButton runat="server" href='<%# "Task.aspx?TaskID=" + MethodtoGenerateTaskId(parameter) %>' target="_blank">LinkButton</asp:LinkButton>
You should define MethodtoGenerateTaskId(parameter) in c# codebehind. Take CommandArgument as a parameter to this method.
protected string MethodtoGenerateTaskId(string command_arg)
{
int rowIndex = int.Parse(command_arg.ToString());
Hashtable dataItem = grvLeads.Rows[rowIndex].ToHashtable() as Hashtable;
string id = Convert.ToString(dataItem["iTask_id"]); //.Split('|');
string rowIndexid = id.ToString();
return rowIndexid.Trim();
}
and in markup;
<asp:LinkButton runat="server" href='<%# "Task.aspx?TaskID=" + MethodtoGenerateTaskId(Container.PageRecordIndex.ToString()) %>' target="_blank">LinkButton</asp:LinkButton>
and if it works; pls mark it as answer...

How do I correctly add tooltip as a hover over button in Gridview

Here is the ASP
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="button" ButtonType="Image" ImageUrl="~/Images/lock.png" text="Lock Customer" CommandName="lock" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Image" ImageUrl="~/Images/lock_open.png" CommandName="unlock" runat="server" />
I did it two different ways based on research. The works, but I cannot get the tooltip to work.
the works, but when I press it to perform "lock" command, I get the following error:
System.FormatException: Input string was not in a correct format
Here is the cs:
Queries Q = new Queries();
string cmd = e.CommandName.ToString();
if (cmd == "unlock")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = Gridview1.Rows[index];
string arg = row.Cells[3].Text.ToString();
int c = Convert.ToInt32(arg);
Q.UpdateRecord("UPDATE [tAccounts] SET [Status] = 'Good' WHERE [contractID] = " + c);
Search();
}
if (cmd == "lock")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = Gridview1.Rows[index];
string arg = row.Cells[3].Text.ToString();
int c = Convert.ToInt32(arg);
Q.UpdateRecord("UPDATE [tAccounts] SET [Status] = 'Locked' WHERE [contractID] = " + c);
Search();
}
The line "int index = Convert.ToInt32(e.CommandArgument) ... e.CommandArgument is NULL on cmd == lock, but not on cmd == unlock.
All I want to do is add a tooltip to my buttonfield type: image.
The row index is automatically added to the command argument for a ButtonField, but not a TemplateField (or any other kind of field). You'll have to do it manually by setting the CommandArgument property on your ImageButton:
<asp:ImageButton ID="button"
ButtonType="Image"
ImageUrl="~/Images/lock.png"
text="Lock Customer"
CommandName="lock"
CommandArgument="<%# Container.DataItemIndex%>"
runat="server"
/>
source (see note at bottom of "Remarks")
Take a look at bootstrap, there you can find ways to add tooltips on varoius elements.

Bind a HiddenField within a gridview

I want to bind a Hidden Field because I want to pass a value from code behind to the asp:Parameter Name="HOME_TEAM_COACH_ID" Type="Int32".
My asp:
<asp:FormView ID="FormView1" runat="server" OnItemUpdated="FormView1_ItemUpdating" >
<EditItemTemplate>
HOME_TEAM:
<asp:DropDownList ID="DropDownListHometeam" runat="server"
DataSourceID="SqlDataGetTeams"
DataTextField="NAME" DataValueField="ID" SelectedValue='<%# Bind("HOME_TEAM_ID") %>'>
</asp:DropDownList>
<asp:HiddenField runat="server" ID="testLabel" Value='<%# Bind("HOME_TEAM_COACH_ID") %>' />
</EditItemTemplate>
And c# behind is:
protected void FormView1_ItemUpdating(object sender, FormViewUpdatedEventArgs e)
{
if (FormView1.CurrentMode == FormViewMode.Edit)
{
DropDownList HomeTeamId = FormView1.FindControl("DropDownListHometeam") as DropDownList;
string team = string.Format("{0}", HomeTeamId.Text);
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BasketballConnectionString1"].ToString());
conn.Open();
string queryHome = "SELECT dbo.COACH.ID, dbo.COACH.SURENAME FROM dbo.COACH INNER JOIN dbo.GAMES ON dbo.COACH.TEAM_ID = dbo.GAMES.HOME_TEAM_ID WHERE (dbo.GAMES.HOME_TEAM_ID =" + team + ")";
SqlCommand cmd = new SqlCommand(queryHome, conn);
var Home_Coach_Id = cmd.ExecuteScalar().ToString();
HiddenField HomeCoachIdLabel = FormView1.FindControl("testLabel") as HiddenField;
HomeCoachIdLabel.Value = Convert.ToString(Home_Coach_Id);
conn.Close();
I want Help with the last four lines where I want to pass the Home_Coach_Id value to bind the asp:HiddenField ID="testLabel" Value='<%# Bind("HOME_TEAM_COACH_ID") %>'.
When I click update, it doesn't change the value in database. (When I debug, in the last lines it gives me the correct HomeCoachIdLabel.Value.)
any suggestions?
You do not need the explicitly set the HiddenField's Value property, because it is done by the <%# Bind("HOME_TEAM_COACH_ID") %> in your markup.
I believe your problem is that you are not returning the HOME_TEAM_COACH_ID from your query to the database in your SELECT statement:
SELECT dbo.COACH.ID, dbo.COACH.SURENAME FROM dbo.COACH
INNER JOIN dbo.GAMES ON dbo.COACH.TEAM_ID = dbo.GAMES.HOME_TEAM_ID
WHERE (dbo.GAMES.HOME_TEAM_ID =" + team + ")
The problem is that it needs the method prerender and not the method onitemupdated.
asp:FormView ID="FormView1" runat="server" OnPreRender="FormView1_OnPreRender" >
and also in c#
protected void FormView1_OnPreRender(object sender, FormViewUpdatedEventArgs e)
{
It also works when I put it in page load{ }.
The next step is to make the insert event....

How to make link button on grid view invisible when I click on it?

I have a grid view with link buttons. When clicking on it, I want to perform some operation, and also need to make the clicked link button invisible. How to make it invisible?
My code:
<asp:TemplateField ShowHeader="true" HeaderText="Theory">
<ItemTemplate>
<asp:LinkButton ID="lb_theory" runat="server" CausesValidation="false" CommandArgument='<%#Eval("student_id")%>' OnClientClick="this.disabled = true; " CommandName="theory_remove" Text="Remove"
command = "lnk_Click" ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="true" HeaderText="Practical">
<ItemTemplate>
<asp:LinkButton ID="lb_practical" runat="server" CausesValidation="false"
CommandArgument='<%#Eval("student_id")%>' CommandName="practical_remove" Text="Remove"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
and
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "theory_remove")
{
string st_id = Convert.ToString(e.CommandArgument.ToString());
string t_id = (string)Session["test"];
SqlConnection con = obj.getcon();
con.Open();
string theory_state = "0";
SqlCommand cmd = new SqlCommand("update student_vs_testsession_details set theory='" + theory_state+ "' WHERE student_id='" + st_id + "' and testsession_id='" + t_id + "'", con);
int temp = cmd.ExecuteNonQuery();
}
}
Try this way
protected void gridview__RowCommand(object sender, GridViewRowEventArgs e)
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
LinkButton lnkbtn = (LinkButton)row.FindControl(”lnkbtnActionNames”);
lnkbtn .Visible = false;
}
I would personally use Knockout JS or jQuery to manage all my client side functionality just as hiding and manipulating html elements.
Add this to your GridView1_RowCommand event
LinkButton mybutton = (LinkButton)sender;
mybutton.Visible = false;
use javascript to hide that. Add onclientclick event and write code in javascript to hide that. First client code will run and then server side. So the button will be hide at that time.

Categories

Resources