GridView Remove one definition - c#

I'm trying to create a web page with the aps.net framework and I connect to the SQL server successfully and I want to display the data from the database in the Grid View and there are a search box and dropdown list but there is an error when I try to search
this is the error message:
Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition.
and my code viewpage1.aspx
the GridView
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" ForeColor="Black" GridLines="Vertical" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" Format="dd/MM/yyyy" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="InvoiceID" DataSourceID="SqlDataSource3">
<AlternatingRowStyle BackColor="#CCCCCC" />
-and this the sqldatasource
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:connStr %>" SelectCommand="Select * from [Portal].[fn_GetInvoices] (#SearchText) where CompanyCode=#CompanyCode and InvoiceDate between #fromDate and #toDate">
<SelectParameters>
viewpage1.aspx.cs
sqlcomm.CommandText = sqlquery;
sqlcomm.Connection = sqlconn;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqlcomm);
adapter.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();

This is a common error message.
I OFTEN use the wizards to build a gridview I use this:
From above, I choose create new data source.
I let the wizard run.
BUT THEN we wind up with some MESSAY sqldatasource in the web page. I do NOT like them, and they NEAR ALWAYS just cause you pain.
So, what I will then do this:
Remove the sqldata source from the web markup - you don't' need that mess anyway.
eg this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:CSharpWebApp.Properties.Settings.TEST4 %>"
SelectCommand="SELECT [ID], [Fighter], [Engine], [Thrust], [Description], [ImagePath]
FROM [Fighters]"></asp:SqlDataSource>
DELETE the above!!!!
Now WHEN you WILL use code to load up the Gridview? Then you ALSO must turn off (remove) the fact that you NOT GOING to use the sql data source anymore.
So in your GV, remove this:
So, all that error message is telling you is you are trying to set the data source in "code" but you ALREADY have a sql datasource setup in the markup.
So, get in the habit of blowing out and removing the sqldata source on the page, and ALSO remove the GV data source setting in the markup.
So, now say I will have this GV, and NOT have ANY data source in the markup in the web page. (and I recommend you do this). So, I still VERY often use the wizards. Even for a dropdown list, a gridview, repeaters, and even listview (my favorite).
So, run wizards - build the markup
Then blow out (remove) the SqlDataSource, and the
DataSourceID="SqlDataSource1" from the control (in this case gv).
So, as noted, you cannot have BOTH a DataSourceID="SqlDataSource1" and THEN try to use code. It is one or the other - and that's what the error message is telling you.
So, now we have this markup:
(and the wizards generated most of this for me!!!)
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" >
<Columns>
<asp:BoundField DataField="Fighter" HeaderText="Fighter" />
<asp:BoundField DataField="Engine" HeaderText="Engine" />
<asp:BoundField DataField="Thrust" HeaderText="Thrust" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:ImageButton ID="btnImage" runat="server" Height="68px" Width="149px"
OnClientClick ="popimage(this);return false"
ImageUrl = '<%# Eval("ImagePath") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Just nice clean markup - no Sqldatasource junk.
Now we are free to write normal code like a normal human, and we can fill the grid like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters", conn))
{
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
And our results are now this:
Ok, so now lets add a search box above the GV to search the GV.
Say you can type in the first few chars of the Fighter jet name, and we want to filter by that:
So, drop in a text box above the GV, + search button.
We now have say this:
<asp:Label ID="Label1" runat="server" Text="Search for Fighter jet" Font-Size="Large"></asp:Label>
<asp:TextBox ID="txtSearch" runat="server" Style="margin-left:15px" Font-Size="Large"></asp:TextBox>
<asp:Button ID="cmdSearch" runat="server" Text="search"
style="margin-left:15px" CssClass="btn"
/>
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" >
<Columns>
So, now the page with searching looks like this:
Say we search for Lockheed - but even just typing in Lock would be fine.
thus:
And now our code can say be this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid("");
}
void LoadGrid(string MySearch)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters ", conn))
{
if (MySearch != "")
{
cmdSQL.CommandText += #" WHERE Fighter LIKE #Fighter + '%'";
cmdSQL.Parameters.Add("Fighter", SqlDbType.NVarChar).Value = MySearch;
}
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
protected void cmdSearch_Click(object sender, EventArgs e)
{
LoadGrid(txtSearch.Text);
}
}
So, I am STRONG suggesting that you DUMP the sqldata source on the web page markup. Such Sqldata soruces on the page can be great for one time load or data display. But the VERY instant you want control, filters, and need to use code?
Quite much the SAME instant it is time to drop and toss out and remove the data source from the web markup. You be glad you did, and as you can see, you now have 100% EASY AND SIMPLE control of the data you shove into the GV, and that includes endless possible use of simple code and buttons to add filters etc. to that data.

Related

Gridview.Databind() not refresh the data

First of all, sorry if I make mistakes in english...
I'm making a web with c#, and I have some problems for refresh the data displayed in the GridView
I'm getting the data throw the SqlDataSource defined at the aspx view:
<asp:SqlDataSource ID="PRODUCTOS_CON_STOCK" runat="server" ConnectionString="<%$ ConnectionStrings:XXXX %>" ProviderName="<%$ ConnectionStrings:XXX.ProviderName %>" DataSourceMode="DataSet" SelectCommand=" select EAN, CODART..... "> </asp:SqlDataSource>
When I click a button, I update some data in the database, and I want refresh de GridView with the new data, without reload the page.
I'm making: gridView.DataBind();, but that doesn't refresh the data in the GridView.
(At the database is updated)
The GridView is inside of an UpdatePanel.
I was trying some things, like:
Reassing the DataSourceID and make the gridView.DataBind();
Assing the DataSourceID in null, make the gridView.DataBind();, and alter reassing the DataSourceID and make the gridView.DataBind();
I tried too:
DataSourceSelectArguments argumentos = new DataSourceSelectArguments();
PRODUCTOS_CON_STOCK.Select(argumentos);
gridView.DataBind();
Set the UpdatePanel to updatemode="Always"
But any of all of that worked...
Someone can help me?
Thanks.
Why not dump the datasource setting on the page of PRODUCTOS_CON_STOCK.
I find that when you need to filtere, load, and play?
Just remove the data source from the markup. So, in your GridView, remove the data source id setting of PRODUCTOS_CON_STOCK, and then delete the data source.
You have to write a BIT more code, but you now have control over the data, and MORE important, control over which parameters you need and want.
So, say I have this markup:
A grid, and also a search/text box to filter the grid.
<asp:Label ID="Label1" runat="server" Text="Search for Fighter jet" Font-Size="Large"></asp:Label>
<asp:TextBox ID="txtSearch" runat="server" Style="margin-left:15px" Font-Size="Large">
</asp:TextBox>
<asp:Button ID="cmdSearch" runat="server" Text="search"
style="margin-left:15px" CssClass="btn" OnClick="cmdSearch_Click" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" CssClass="table" >
<Columns>
<asp:BoundField DataField="Fighter" HeaderText="Fighter" />
<asp:BoundField DataField="Engine" HeaderText="Engine" />
<asp:BoundField DataField="Thrust" HeaderText="Thrust" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:ImageButton ID="btnImage" runat="server" Height="68px" Width="149px"
OnClientClick ="popimage(this);return false"
ImageUrl = '<%# Eval("ImagePath") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Note close - I did build this grid using the wizards. But I THEN removed the Datasource ID for the GV, and removed the Datasource that was created in the markup.
So, now my code to load is this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid("");
}
void LoadGrid(string MySearch)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * from Fighters ", conn))
{
if (MySearch != "")
{
cmdSQL.CommandText += #" WHERE Fighter LIKE #Fighter + '%'";
cmdSQL.Parameters.Add("Fighter", SqlDbType.NVarChar).Value = MySearch;
}
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
GridView1.DataSource = rstData;
GridView1.DataBind();
}
}
}
And I get this:
And note the "optional" filter for the text box. If you type in some text, (I used a "like" match in sql), then the code is only this:
protected void cmdSearch_Click(object sender, EventArgs e)
{
LoadGrid(txtSearch.Text);
}
but, the idea here is often it is much better to dump the SqlDataSoruce placed in the markup, and roll + write your own code. The problem is you can try and set the data source in code, but ALSO WITH a data source on the page - they fight over each other. So, try the above idea - and remove the data source in the markup.
Finally I resolved the issue.
In my case, I was calling in the front, in AJAX, the C# method, that method is an WebMethod HttpPost
The issue was that I was saving in a Session the GridView and the SqlDataSource, and although I was executing the Select statement again, I was obtaining the old's values.
I was saving in a Session that information because the AJAX execute the method direct and the GridView and the SqlDataSource were null
Finally I tried to make a refresh from the GridVeiw by a button, and the info is updated correctly, so, I hided the button, and simulate the click button in AJAX:
$.ajax({
type: 'POST',
url: pageUrl,
data: JSON.stringify({ gridMod: gridMod }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function() {
document.getElementById("<%= btnReload.ClientID %>").click();
},
});
So, the click event call to LoadGrid();, and this one execute:
private void LoadGrid()
{
DataSourceSelectArguments argumentos = new DataSourceSelectArguments();
PRODUCTOS_CON_STOCK.Select(argumentos);
eanList.DataBind();
}
In this way, I can refresh the data "automatically" without clicking in any button

c# Cannot Convert from string to int

I have a gridview that populates from an SQL table and shows two columns, one comes from an integer data column, the other from an nvarchar. Gridview also has a checkbox column
The gridview populates correctly, and after a subset of rows is selected (via checkbox column) I want to insert the selected rows into another SQL table. When populating the variables for the SQL statement however I get the "Cannot Convert from string to int" error on the value that is populated from an int to begin with.
I have tried writing up convert and parse for this statement but still getting the error:
cmd.Parameters.AddWithValue("#PracticeArea", int.Parse(row.Cells["Id"].Value));
cmd.Parameters.AddWithValue("#PracticeArea", Convert.ToInt32(row.Cells["Id"].Value));
cmd.Parameters.AddWithValue("#PracticeArea", Convert.ToInt32(row.Cells["Id"].Text));
All still show the error on the ["Id"] value.
Any thoughts?
Example of the data that is being populated to the gridview is:
PracticeID PracticeName
1 General Surgical Pathology
2 General Pathology/Basic Science
4 Cardiovascular
6 Cytopathology-GYN
7 Cytopathology-nonGYN
Full button command is:
protected void Bulk_Insert(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if ((row.FindControl("CheckBox1") as CheckBox).Checked)
{
string connectionString = WebConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO ReviewerPractice VALUES(#Reviewer, #PracticeArea)", con))
{
cmd.Parameters.AddWithValue("#Reviewer", ReviewerName.Text);
cmd.Parameters.AddWithValue("#PracticeArea", Convert.ToInt32(row.Cells["Id"].Value));
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
}
Full Gridview control is:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
<asp:BoundField DataField="PracticeName" HeaderText="PracticeName" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="Button1" Text="Add Practice Areas" OnClick="Bulk_Insert" runat="server" />
Hope this answers (some?) of the questions from all the comments to date.
The problem is that row.Cells[] is an array, so you need to use it like this:
row.Cells[3].Text
And it's better to use the Parameters for sql like this:
cmd.Parameters.Add("#PracticeArea", SqlDbType.Int).Value = Convert.ToInt32(row.Cells[index].Text;

How can insert values into gridview rows ? ASP.NET ,C#

My question is how can i insert values into gridviews rows.Basically I have created a gridview in which i bound the footer and i want to insert values in the footer.I have create a 'textboxs','dropdownlist' and 'checkboxes'.I want when i insert value and press "Insert" button then values shown in the gridview and again i insert value and press button then show inserted values in the gridview.Here is my gridview image
and i also want to edit and delete rows as well.Here is my code :
aspx code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="104px" ShowFooter="True" Width="463px"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">
<Columns>
<asp:TemplateField HeaderText="Column Name">
<FooterTemplate>
<asp:TextBox ID="name" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Data Type">
<FooterTemplate>
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Allow Null">
<FooterTemplate>
<asp:CheckBox ID="allow_null" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Primary Key">
<FooterTemplate>
<asp:CheckBox ID="primary" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and here is my aspx.cs code :
protected void Button1_Click(object sender, EventArgs e)
{
string name = TextBox1.Text;
string type = DropDownList1.Text;
string allow=Null.Text;
string primary = Primary.Text;
name = ((TextBox)GridView1.FooterRow.FindControl("TextBox2")).Text;
type = ((DropDownList)GridView1.FooterRow.FindControl("DropDownList2")).Text;
allow = ((CheckBox)GridView1.FooterRow.FindControl("allow_null")).Text;
primary = ((CheckBox)GridView1.FooterRow.FindControl("primary")).Text;
}
To use the GridView in this way, with input fields in the footer and a Insert Button that is outside the GridView, you need to make a manual Insert.
I don't know how you perform an Insert using the EF model as I don't currently use it. I guess you could say the "old" way is to use an instance of SqlConnection and SqlCommand. You would use code similar to this inside your Button Click event:
// This is VB. C# is similar, you will have to convert where needed
Using connection As New SqlConnection(connectionString)
Using command As New SqlCommand(queryString, connection)
command.Connection.Open()
command.CommandType = // Typically Text or StoredProcedure as needed
command.Parameters.AddWithValue("#parameter_name1", some_value_1)
command.Parameters.AddWithValue("#parameter_name2", some_value_2)
.
.
.
command.ExecuteNonQuery()
End Using
End Using
queryString is your sql INSERT statement or a stored procedure
command.Parameters is a collection of replaceable parameter in your INSERT statement or Stored Proc.
Addendum
A Gridview is a Data bound control so typically when you use a gridview it's bound to some backing data source. If you are not using a database then you are using some other construct.
If you are using, for example, a DataTable, you would add the new rows and columns to the DataTable using its row and column methods and then rebind the DataTable to the Gridview. You don't add rows and columns directly to a GridView.
See this other SO answer by JonH for an example
In case this helps this is based on the ASPSnippets but modified to be more like you might need. Note that instead of using a DataTable I am using a List where "Row" is a class. It is somewhat a matter of personal preference which one you use. The "Row" class is:
[Serializable]
public class Row
{
public string FieldName { get; set; }
public string FieldType { get; set; }
public Boolean FieldNullible { get; set; }
public Boolean FieldPrimaryKey { get; set; }
}
My names are different from your names. Note that the ASPSnippets sample does not use TemplateFields so I am not. I am not sure if you need to make the "allow"
and/or "primary" fields Boolean so I did not process them in the form. So the ASP.Net form I have is:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Height="104px" Width="463px"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True">
<Columns>
<asp:BoundField DataField="FieldName" HeaderText="Name" ItemStyle-Width="120" />
<asp:BoundField DataField="FieldType" HeaderText="Type" ItemStyle-Width="120" />
</Columns>
</asp:GridView>
<br /><asp:Label ID="Label1" runat="server" Text="Name:"></asp:Label>
<br /><asp:TextBox ID="txtName" runat="server" />
<br /><asp:Label ID="Label2" runat="server" Text="Type:"></asp:Label>
<br /><asp:TextBox ID="txtType" runat="server" />
<br /><asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Insert" />
The code-behind is:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
return;
List<Row> Rows = new List<Row>();
ViewState["Rows"] = Rows;
BindGrid();
}
protected void BindGrid()
{
GridView1.DataSource = (List<Row>)ViewState["Rows"];
GridView1.DataBind();
}
protected void Insert(object sender, EventArgs e)
{
List<Row> Rows = (List < Row >)ViewState["Rows"];
Row r = new Row();
r.FieldName = txtName.Text.Trim();
r.FieldType = txtType.Text.Trim();
Rows.Add(r);
ViewState["Rows"] = Rows;
BindGrid();
txtName.Text = string.Empty;
txtType.Text = string.Empty;
}
One thing I do not like is that the GridView does not show until there is data in it. I assume you can fix that.
This does not implement the editing and deleting.

Better solution to SqlDataSource?

I need to display some data from a view in a SQL Server database on several pages of my website. I've done it by using SqlDataSource within my web.config and then used a GridView control within my .aspx page to display the data.
Now, this works but I read in some forum that it is bad practice to do use SqlDataSource? I will probably need to have the ability for the admin/user to filter the data in the future, so I'm not sure how this would work with my current implementation.
My code so far looks like this :
In the web.config file:
<connectionStrings>
<add name="Test1.ConnectionString"
connectionString="Data Source=...."
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
And something like this in my aspx
<body id="wrap" >
<form runat="server">
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False"
BackColor="White" BorderColor="#CCCCCC"
BorderStyle="None" BorderWidth="1px" CellPadding="3"
DataSourceID="SqlDataSource1" Height="500px" Width="408px">
<Columns>
<asp:BoundField DataField="Title" HeaderText="Title" ReadOnly="True" SortExpression="Title">
<ItemStyle Width="400px" HorizontalAlign="Center" Height="100px" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
</asp:BoundField>
<asp:BoundField DataField="Result" HeaderText="Result" ReadOnly="True" SortExpression="Result" >
<ItemStyle HorizontalAlign="Center" Height="100px" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
</asp:BoundField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#002756" />
<HeaderStyle BackColor="#003466" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#002756" HorizontalAlign="Left" />
<RowStyle ForeColor="#002756" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings: Test1.ConnectionString %>"
SelectCommand="SELECT * FROM [Test1.ConnectionString]">
</asp:SqlDataSource>
</form>
</body>
So my question is is there a better way to implement this, keeping in mind that I will probably need a function for the user/admin to filter the data by certain criteria?
It's not necessarily bad practice to use SqlDataSource... but it does tend to mingle your data access code with your presentation code. Additionally, you can often do better with an ObjectDataSource that wraps your view. There's a little more code involved (you'll have to create a new class somewhere to select from your view), but you end up with methods that can be easily updated or replaced in the future to handle whatever changes you may need.
As mentioned in my comment I would recommend you use the code behind to achieve this as it's much easier to make changes if required in the future. I'm assuming you've got a table in your database named Test1. We'll first create a class to represent this in C# and add a few properties which we'll use later on.
public class Test
{
public string Title { get; set; }
public int Result { get; set; }
}
Now let's create a method which returns a collection of values from your database.
public List<Test> GetData()
{
List<Test> myList = new List<Test>();
string sqlQuery = "Select Title, Result From Test";
string connectionString = ConfigurationManager.ConnectionStrings["Test1.ConnectionString"].ConnectionString; //Read connection string from config file
using (var con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(sqlQuery, con))
{
//Add param here if required.
con.Open(); //Open connection
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Test t = new Test();
t.Title = reader["Title"].ToString();
t.Result = Convert.ToInt32(reader["Result"]);
myList.Add(t);
}
}
}
}
return myList;
}
Finally, you want to set the datasource for the GridView. I'm going to assume you have a page called MyGridPage.aspx open up the MyGridPage.asps.cs and in your Page_Load event you can set the DataSource for your grid as:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Test t = new Test();
GridView1.DataSource = t.GetData();
GridView1.DataBind();
}
}
If you wanted to filter your Sql query by for example username you'll change it as:
string sqlQuery = "Select Title, Result From Test Where username = #username";
Then you can pass in the #username parameter as:
cmd.Parameters.Add("#username", SqlDbType.NVarChar).Value = myUsername;
myUsername can be of someone who's logged into your app. You will pass the parameter(s) before you open the connection. Passing parameters will also prevent sql injection which I suggest you read up on in case you're not aware.
Note: it is recomenned to make use of using block to ensure the connection object is closed and disposed correctly.
You can programmatically set the data source of the grid view.
protected void Page_Load(object sender, EventArts e)
{
using(SqlConnection conn = new SqlConnection(connectionString))
{
string query = "SELECT * FROM Test"; //your SQL query goes here
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
da.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
cmd.Dispose();
da.Dispose();
}
}

Dynamic deletion from SQL database for .NET

I have a SQL database that store values input via a text box. This then displays the values of that database on my output screen via a gridbox. Is there a way I can give the user the an option of which column he wants to delete? Like a delete button near the value in the gridbox.
If not how do I delete a variable column number in SQL. Like, If the user wants to delete line say 10. How do I incorporate that in my SQL delete command.
Should it incorporate the 'top' command? If so how?
protected void Button3_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
sc.ConnectionString = ("Data Source=abc; Initial Catalog=VisualStudioTest; User ID=USER; Password=PASS");
sc.Open();
SqlCommand com = new SqlCommand();
com.Connection = sc;
com.CommandText = ("delete from notes");//initially I've kept this to delete everything.
com.ExecuteNonQuery();
sc.Close();
Response.Redirect(Request.RawUrl);
}
Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
OnSelectedIndexChanged="GridView1_SelectedIndexChanged1">
<Columns>
<asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:VisualStudioTestConnectionString3 %>"
SelectCommand="SELECT [Notes] FROM [Notes]"
OnSelecting="SqlDataSource1_Selecting">
</asp:SqlDataSource>
i assume your goal is to delete a single row.
the simplest way that comes to my mind is to add a identity field as a key for the table, add the new column to the DataKeyNames list of the GridView and then add a parameter to the DeleteQuery in the SqlDataSource:
delete from notes where identityCol = #identityCol;
the last step is to add the delete control to the Gridview.

Categories

Resources