Retrieving filename column form Gridview - c#

I have a Gridview which displays the filenames in the database.
I have written code for deleting filename entry from database, but I also want to delete it from the directory, so how do I retrieve filename from Gridview ?
I don't want to execute another select command for retrieving filename.
Code :
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int Fid = (int)GridView1.DataKeys[e.RowIndex].Value;
sdsFiles.DeleteCommand = "Delete from Files where Fid = #id";
sdsFiles.DeleteParameters.Clear();
sdsFiles.DeleteParameters.Add("id",Fid.ToString());
sdsFiles.Delete();
System.IO.Directory.Delete(Server.MapPath("~/Data/"));
}
Thanks.

Use the following code and do steps;
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int Fid = (int)GridView1.DataKeys[e.RowIndex].Value;
sdsFiles.DeleteCommand = "Delete from Files where Fid = #id";
sdsFiles.DeleteParameters.Clear();
sdsFiles.DeleteParameters.Add("id",Fid.ToString());
sdsFiles.Delete();
string fileName = ((Label)GridView1.Rows[e.RowIndex].FindControl("Label1")).Text;
System.IO.File.Delete(Server.MapPath("") + "\\" + fileName);
}
you must go to gridview columns
window
Convert to file name column to
TemplateField
Save and Exit GridView Columns window
Go to Files column template design
Set label id "Label1"
Go to code and use it

For performance reasons I, wouldn't go overboard adding lots of keys with this, but you can set the GridView's DataKeys property to include the filename column as well as the fid that you already set by setting the GridViews DataKeyNames property equal to "FID,Filename", then retrieve the DataKey by row during your delete method using the GridView1.DataKeys[e.RowIndex].Values method instead, where retrieve the DataKey by index, so if your DataKeys are "FID,filename" FID would be GridView1.DataKeys[e.RowIndex].Values[0] and filename would be GridView1.DataKeys[e.RowIndex].Values[1].

I get the string (file name) direct this way:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView1.SelectedIndex = e.RowIndex;
string fileName = GridView1.SelectedRow.Cells[1].Text;
System.IO.File.Delete(Server.MapPath("") + "\\" + fileName);
int Fid = (int)GridView1.DataKeys[e.RowIndex].Value;
sdsFiles.DeleteCommand = "Delete from Files where Fid = #id";
sdsFiles.DeleteParameters.Clear();
sdsFiles.DeleteParameters.Add("id",Fid.ToString());
sdsFiles.Delete();
GridView1.SelectedIndex = -1;
}
Maybe there is ever faster, I am not sure.

Related

select row from a gridview that during the execution has a new datasource

On the first column is the id and want to select it to be redirected to a page that has more details that row.
He goes good if datasource is not changed but if it is modified or receive ID of the initial data, or gives me error for that initially did not have many rows.
My code is:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridView1.DataBind();
GridViewRow row = GridView1.SelectedRow;
string strCell = row.Cells[1].Text;
string myPageUrl = "Meci.aspx?ID=" + strCell;
Response.Redirect(myPageUrl);
}
Please tell me how can I change it to work well!

DataGridView and SQL query name

I have a function that gets all the data from database (also the column names) and shows it in a DataGridView.
The problem is that the DataGrid show also the column name. How can I edit the columns name? I already tried
dataGridView1.Columns[0].Name = "xxx";
without success.
private void PriceChange_Load(object sender, EventArgs e)
{
DbCards d = new DbCards();
dataGridView1.DataSource = d.GetAllcards().Tables[0];
}
GetAllcards() is select * from Cards.
If you want to change the header text displayed by a DataGridViewColumn you need to use the HeaderText property
dataGridView1.Columns[0].HeaderText = "xxx";
Set dataGridView1.Columns[0].HeaderText instead

QueryString to Textbox

I have a table tblProfile, which contains fields with Id, Name, Address. I have 2 aspx page, which are Home.aspx and Here.aspx. On my Home.aspx I have used this code to pass the Id in my Here.aspx:
<asp:HyperLink ID="link" runat="server" NavigateUrl="Here.aspx?id={0}"
Font-Names="Times New Roman" Font-Size="Medium" >Click here</asp:HyperLink>
In code behind Home.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
string bID = Request.QueryString["Id"];
if (string.IsNullOrEmpty(Id))
{
Response.Redirect("Here.aspx?", true);
}
ViewState["Id"] = Id;
link.NavigateUrl = String.Format(link.NavigateUrl, Id);
}
I don't have any problem with passing the Id to url in 2nd page. But what I want right now is, on my Here.aspx, I have 3 textboxes which supposed to be filled by the Id, Name and Address of the certain Id that passed from the Home.aspx. Tried many but had no luck at all. Any help would be appreciated. By the way, I'm using asp.net with c#.
We are having two solution for it
Solution 1 : User Previous page property in asp.net so that you no need to pass ID. i.e.
protected void Page_Load(object sender, EventArgs e)
{
// Find the name on the previous page
TextBox txt = (TextBox)Page.PreviousPage.FindControl("txtNameText");
if (txt != null)
txtName.Text = Server.HtmlEncode(txt.Text);
else
txtName.Text = "[Name Not available]";
}
Solution 2 : Get ID from query string and get Data by ID in assign on text box text property.i.e.
protected void Page_Load(object sender, EventArgs e)
{
// Get value from query string
string profileID = Request.QueryString["Id"];
// Fetch data from database by ID
DataTable dt = FetchEmployeeDataByID(ProfileID);
txtName.text = dt.rows[0]["Name"].tostring();
}
From your reply on comments, I suggest to do the following:
Load your data in Here.aspx back-end (.cs file) by the Id that you retrieve from query string
Show the loaded data into your desired textbox.
You can get the name and address by retrieving the profile data from the database using the Id from the query string as the key.
So in your Here.aspx's code behind:
protected void Page_Load(object sender, EventArgs e)
{
string profileID = Request.QueryString["Id"];
// Retrive profile in your db..
var profile = Profiles.Get(p => p.ProfileID == profileID);
// Populate the textboxes
txtId.Text = profileID;
txtName.Text = profile.Name;
txtAddress.Text = profile.Address;
}

Search on gridView does nothing

I have a gridVIew which has a datasource of a table in Access database.
I want to add search functionality on this gridview. I added a textBox and search button. My Code is
protected void btnSearchService_Click(object sender, EventArgs e)
{
string SearchField = TextBox1.Text;
string searchSQL = "SELECT * FROM LocalService WHERE ServiceName LIKE '%" + SearchField + "%'";
SqlDataSource1.UpdateCommand = searchSQL;
SqlDataSource1.Update();
}
But in browser when I click Search button, I see nothing happens. DO I have to add code on page load or somewhere?
It worked. I have replaced following lines
SqlDataSource1.UpdateCommand = searchSQL;
SqlDataSource1.Update();
with these lines
SqlDataSource1.SelectCommand = searchSQL;
GridView1.DataBind();

how to write sql query from one page to another

I am currently working on my first website. The problem I have encountered is the following: I have created a paged titled "CustomerList" that obviously list customers from an sql server DB. I have made the records clickable without using the select button that is included in the GridView. When I click a record, it takes me to my desired page. However, I can't seem to find a way to write an sql query from that click event to my desired page. The following is my code for the click event:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
if (row.RowIndex == 0)
{
Response.Redirect("UsageHistoryPage.aspx? EntityID="
+ row.Cells[0].Text);
}
}
As you can see, when I click an index, I go to the "UsageHistoryPage". I've also added row.cells.[0] to take that data and write it to the UsageHistoryPage, which in my case, would be the customers name at the top of the page. Can someone please help me with this? Does anyone have a good tutorial link? thanks.
You can try with this code - Add this code on your UsageHistoryPage
var input = Response.QueryString["EntityId"];
var connectionString = "...";
var queryString = "SELECT Name FROM TABLE WHERE COLUMN=#EntityId";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
using(var command = new SqlCommand(queryString, connection))
{
Command.Parameters.AddWithValue("#EntityId",input)
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
Response.Write(String.Format("For Rick Your Name is here{0}", reader[0]));
}
}
}
#Rick you may want to look at how to check if a row is selected for example you don't need the for loop but in my case example need to check if RowIndex is = 1 or > 0 not ==0
private void myButton_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in usersGrid.Rows)
{
if (this.usersGrid.SelectedRows.Count == 1)
{
// get information of 1st column from the row
string selectedUser = this.usersGrid.SelectedRows[0].Cells[0].ToString();
}
}
}
What you need to do is something like this to make sure that a Row has been selected
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
DataGridViewRow row = GridView1.SelectedRow;
if (this.row.SelectedRows.Count == 1)
{
Response.Redirect("UsageHistoryPage.aspx?EntityID=" + row.SelectedRows[0].Cells[0].ToString());
}
}
If you want to have the Customer's name show up, on the Page Load of the UsageHistorPage.aspx add this code
String strCustName = Request.QueryString["EntityID1"];
this.Page.Title = strCustName;
try something like that.. please let someone here know if any of the ideas are working for you.

Categories