Better solution to SqlDataSource? - c#

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();
}
}

Related

GridView Remove one definition

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.

Updating Database with sessions not working C# SQL

So my code brings across the searched for userID of a lecturer and the ModuleID previously selected by the user. However it breaks on this line;
myCommand.ExecuteNonQuery();
The error is;
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near '('.
I don't know why it does it but I can see that my stuff is being pulled across when I use a break point.
Front end code:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
SelectCommand="SELECT Lecturer_Records.UserID, Lecturer_Records.FirstName, Lecturer_Records.Surname, Lecturer_Records.PhoneNumber, Users.Email
FROM Lecturer_Records
INNER JOIN Users ON Lecturer_Records.UserID = Users.UserID
WHERE (Users.Email = #email)">
<SelectParameters>
<asp:QueryStringParameter Name="email" QueryStringField="searchlects" />
<asp:SessionParameter Name="ModuleID" SessionField="ModuleID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="SearchResult" runat="server" AutoGenerateColumns="False" AutoGenerateSelectButton="True" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="SearchResult_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="UserID" HeaderText="UserID" SortExpression="UserID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="Surname" HeaderText="Surname" SortExpression="Surname" />
<asp:BoundField DataField="PhoneNumber" HeaderText="PhoneNumber" SortExpression="PhoneNumber" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
</Columns>
</asp:GridView>
And my C# code
protected void SearchResult_SelectedIndexChanged(object sender, EventArgs e)
{
// open new connection
SqlConnection connection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
connection1.Open();
string SearchUser = SearchResult.SelectedRow.Cells[1].Text;
string Module = (string)Session["ModuleID"];
SqlCommand myCommand = new SqlCommand("UPDATE [Modules] SET (UserID = '" + SearchUser + "') WHERE (ModuleID = '" + Module + "')", connection1);
myCommand.ExecuteNonQuery();
// move on to home page
Response.Redirect("APMDefault.aspx");
}
You don't need any ( or ) in your command. They breaks your sql syntax. Just delete them.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Based on your column names, they seems as a numerical types. That means, you might need to delete single quotes as well. If you use prepared statements, you will not need this of course.
And use using statement to dispose your connection and command.
using(var connection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
using(var myCommand = connection1.CreateCommand())
{
myCommand.CommandText = #"UPDATE Modules SET UserID = #userid
WHERE ModuleID = #moduleid";
myCommand.Parameters.Add("#userid", SqlDbType.NVarChar).Value = SearchUser;
myCommand.Parameters.Add("#moduleid", SqlDbType.NVarChar).Value = Module;
// I assumed your column types are nvarchar
connection1.Open();
myCommand.ExecutenonQuery();
// move on to home page
Response.Redirect("APMDefault.aspx");
}
But really, those columns are seem as numerical types. Either you can their type or change their name that points their types as character.

The connection was not closed. The connection's current state is open. (Multiple Image Upload)

While Uploading multiple images i was getting error as Maximum request length exceeded but When I increased the size from the Web.Config file now I am getting error as The connection was not closed. The connection's current state is open.
Dont know why.
Please check the code and do let me know where I am mistaken
protected void btnAdd_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == false)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", "<script>alert('Please select the file.')</script>", false);
}
else
{
foreach (var file in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(file.FileName);
FileUpload1.SaveAs(Server.MapPath("/GalleryImages/" + filename));
SqlCommand cmd = new SqlCommand("Insert into tbl_gallery_stack(gallery_id, image_title, image_description, image_path) values (#gallery_id,#image_title,#image_description,#image_path)", conn);
cmd.Parameters.AddWithValue("#gallery_id", ddlImagesId.SelectedValue);
cmd.Parameters.AddWithValue("#image_title", txtImageTitle.Text);
cmd.Parameters.AddWithValue("#image_description", txtImageDescription.Text);
cmd.Parameters.AddWithValue("#image_path", filename);
conn.Open();
cmd.ExecuteNonQuery();
BindGrid();
}
}
}
My web.config file code:-
<system.web>
<httpRuntime maxRequestLength="1073741824" />
</system.web>
Latest thing happening
When I upload multiple image, I am not able to view in the gridview. And also in the table the multiple entries get inserted..
See the code:-
<asp:GridView ID="grdGalleryData"
runat="server"
Width="100%" border="1"
Style="border: 1px solid #E5E5E5;"
CellPadding="3"
AutoGenerateColumns="False"
AllowPaging="True"
PageSize="3"
OnPageIndexChanging="grdGalleryData_PageIndexChanging"
CssClass="hoverTable"
DataKeyNames="Id"
>
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="30" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:CheckBox ID="chkDelete" runat="server" />
</ItemTemplate>
<HeaderStyle CssClass="k-grid td"></HeaderStyle>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:BoundField DataField="gallery_id" HeaderText="Id" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="image_title" HeaderText="Gallery title" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:BoundField DataField="image_description" HeaderText="Gallery Description" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td" />
<asp:TemplateField HeaderText="Images" ItemStyle-Width="25" HeaderStyle-CssClass="k-grid td">
<ItemTemplate>
<asp:Image ID="imgDisplay" runat="server" ImageUrl='<%#Getimage(Eval("image_path").ToString()) %>' Width="100px" Height="100px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Also see the code behind:-
protected void btnAdd_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == false)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", "<script>alert('Please select the file.')</script>", false);
}
else
{
foreach (var file in FileUpload1.PostedFiles)
{
string filename = Path.GetFileName(file.FileName);
FileUpload1.SaveAs(Server.MapPath("/GalleryImages/" + filename));
SqlCommand cmd = new SqlCommand("Insert into tbl_gallery_stack(gallery_id, image_title, image_description, image_path) values (#gallery_id,#image_title,#image_description,#image_path)", conn);
cmd.Parameters.AddWithValue("#gallery_id", ddlImagesId.SelectedValue);
cmd.Parameters.AddWithValue("#image_title", txtImageTitle.Text);
cmd.Parameters.AddWithValue("#image_description", txtImageDescription.Text);
cmd.Parameters.AddWithValue("#image_path", filename);
conn.Open();
cmd.ExecuteNonQuery();
BindGrid();
conn.Close();
}
}
}
protected string Getimage(string img)
{
if (img != "")
return ("~/GalleryImages/" + img);
else
return ("Images/noimg.gif");
}
BindGrid method
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropdownlist();
BindGrid();
}
}
private void BindGrid()
{
string conString = ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString;
SqlCommand cmd = new SqlCommand("Select Id, gallery_id, image_title, image_description, image_path from tbl_gallery_stack order by Id desc");
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
grdGalleryData.DataSource = dt;
grdGalleryData.DataBind();
}
}
}
}
Since you are looping over a collection of files and then inserting data to the database, please instantiate the connection within a using block(so that it would be disposed properly) and also if you want to see all those images uploaded at a time in Grid, then I suggest you move BindGrid() function out of the ForEach loop.
Some sample code below:
foreach (var file in FileUpload1.PostedFiles)
{
try
{
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Server.MapPath("/GalleryImages/" + filename)); //Save each file to disk.
//Also please evaluate you requirement and if you are supposed to loop over relatively
// large collection then you can opt for some batch insert/update of records at-a-go
// instead of calling database multiple times, if your database offer support.
using(var conn = new SqlConnection("YOUR CONNECTION STRING VALUE HERE"))
using(var cmd = new SqlCommand("Insert into tbl_gallery_stack(gallery_id,image_title, image_description, image_path) values (#gallery_id,#image_title,#image_description,#image_path)", conn))
{
cmd.Parameters.AddWithValue("#gallery_id", ddlImagesId.SelectedValue);
cmd.Parameters.AddWithValue("#image_title", txtImageTitle.Text);
cmd.Parameters.AddWithValue("#image_description", txtImageDescription.Text);
cmd.Parameters.AddWithValue("#image_path", filename);
conn.Open();
cmd.ExecuteNonQuery();
}
}
catch(Exception ex) //I suggest you handle all those db/network specific exceptions first
{
//Log the exception details here and either continue over the loop or return based on application requirement.
}
}
BindGrid(); //Assuming you are getting data from database inside this method and binding to Grid.
Also to ensure data integrity it would be better if you move disk file storage logic to end of the loop perhaps setting the entire database & file logic in a try catch block. So that if some error occur in database your disk file also won't be created unmapped.
Hope this may provide some help to your problem.
Close your connection after execute your query.
conn.Open();
cmd.ExecuteNonQuery();
//Close connection
conn.Close();
You're receiving the exception because you never close your connection. An SqlConnection generally can only ever execute one command at a time. Simply add:
conn.Close();

In c#, my datagrid is not showing the rows

I have a datagrid which I fill with a data set, several are done this way and they work, just one does not, why?
Code
<asp:DataGrid ID="dgServer" runat="server"
AutoGenerateColumns="False" AllowSorting="True"
ondeletecommand="dataGrid1_DeleteCommand"
oneditcommand="dataGrid1_EditCommand"
OnSortCommand="dataGrid1_SortCommand">
<AlternatingItemStyle BackColor="#C1D0EC" />
<Columns>
<asp:EditCommandColumn CancelText="Cancel" EditText="Editar"
UpdateText="Update">
<HeaderStyle Wrap="False" />
<ItemStyle Wrap="False" />
</asp:EditCommandColumn>
<asp:ButtonColumn CommandName="Delete" Text="Borrar"></asp:ButtonColumn>
<asp:BoundColumn DataField="Id" HeaderText="Id" SortExpression="Id"
Visible="False"></asp:BoundColumn>
<asp:BoundColumn DataField="Server" HeaderText="Servidor"
SortExpression="Server" >
</asp:BoundColumn>
<asp:BoundColumn DataField="Port" HeaderText="Puerto" SortExpression="Port"
></asp:BoundColumn >
<asp:BoundColumn DataField="User" HeaderText="Usuario" SortExpression="User"
></asp:BoundColumn >
<asp:BoundColumn DataField="Password" HeaderText="Password" SortExpression="Password"
></asp:BoundColumn >
<asp:BoundColumn DataField="PassAuten" HeaderText="PassAut" SortExpression="PassAut">
</asp:BoundColumn>
</Columns>
<EditItemStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="#0B63A2" ForeColor="White" />
</asp:DataGrid>
How is done in every other and it works:
public void LlenarDataGridServer()
{
//read = Con.executar_re("Select * from SMTP");
//dataGrid1.DataSource = read.Tables[0];
//dataGrid1.DataBind();
DataSet verServer = Con.executar_re("select * from dbo.smtp");
dgServer.DataSource = verServer.Tables[0];
dgServer.DataBind();
}
So whats up, this is killing me. Thanks.
Edit: Yes the table is set up, I can access the data from sql server and is 1 row which I plan to update.
2 Edit: The same lines are filling other DG like
public void LlenarDatagridConsecutivos()
{
read = Con.executar_re("select * from TypeCConsecutiveDocument");
dgConsecutivos.DataSource = read.Tables[0];
dgConsecutivos.DataBind();
}
And the Con.etc:
public DataSet executar_re(string comando)
{
try
{
connnection01.Open();
SqlCommand command01 = new SqlCommand();
command01.CommandText = comando;
command01.Connection = connnection01;
SqlDataReader re01 = command01.ExecuteReader(CommandBehavior.CloseConnection);
DataSet ds = Convert(re01);
re01.Close();
connnection01.Close();
return ds;
}
catch (SqlException sqle)
{
System.Diagnostics.Debug.WriteLine(sqle.ToString());
DataSet ds = new DataSet();
return ds;
}
I don't know what is going on in that Convert method, but, see this link about how to use a SqlDataReader: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx
Should be something like this:
List<IDataRecord> records = new List<IDataRecord>();
while(re01.Read())
{
//add record to list
records.Add((IDataRecord)re01);
}
//records now has your list of data.
re01.close();
I got it, it was something really strange:
I change the table name from smtp to mailServer
I put the column name's in [name]
I got rid of the DG and put it in a label which changes
I think is more likely to be 1, 2.
Something funny is going on with some name :o
Edited: to look better

Appending LINQ to exist datasource/gridview in C#

I have the following in my .aspx page:
<asp:GridView ID="Table1" runat="server" AutoGenerateColumns="False" BorderColor="Black" OnRowCreated="Table1_RowCreated" OnRowDataBound="Table1_RowDataBound" CellPadding="3" CellSpacing="0" DataSourceID="Table1DataSrc" DataKeyNames="Field1">
<Columns>
<asp:BoundField DataField="Field1" HeaderText="Field1" SortExpression="Field1">
<ItemStyle HorizontalAlign="Left" Font-Size="8" Wrap="false" />
<HeaderStyle CssClass="header" Font-Size="8" />
</asp:BoundField>
</Columns>
</asp:GridView>
Where the gridview has a DataSource that loads a few fields. In my C# code behind, I have the following function which runs a LINQ query to process a stored procedure (on a different server than my other datasource)
private void RenderTables()
{
SqlDataAdapter adapter = new SqlDataAdapter();
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("sp_special", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#AmIY", "Y");
adapter.SelectCommand = cmd;
adapter.Fill(dt);
adapter.Dispose();
conn.Close();
}
var enumvar = dt.AsEnumerable();
var query = from x in enumvar
orderby x.Field<string>(3)
select new
{
Field3 = x.Field<string>(3),
Field4 = x.Field<int>(4),
};
//I do some data manipulation using LINQ, but omitted here
//do something with query.....
}
How would I add new columns Field3 and Field4 to my Gridview and bind these new records? I do not want to store anything in temp tables on either servers
it will work like this...
<asp:BoundField DataField="Field3" HeaderText="Field3" SortExpression="Field3">
<asp:BoundField DataField="Field4" HeaderText="Field4" SortExpression="Field4">

Categories

Resources