Auto generated Gridview - Change columns width - c#

i'm in a trouble!
I'm generating a lot of gridviews dinamically, with dinamic values to columns.
The columns are ever the same.
I want to know how can i set the size of this columns.
That's my code, with my effort.
private void generateControls( List<List<DataRow>> grids)
{
DataTable dt = new DataTable();
int i = 0;
foreach (List<DataRow> lst in grids)
{
dt = lst.CopyToDataTable();
GridView grv = new GridView();
grv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromName("#cccccc");
grv.HeaderStyle.BackColor = System.Drawing.Color.Gray;
grv.Width = new Unit("100%");
//grv.RowStyle.Wrap = false;
grv.RowStyle.Width = new Unit("100%");
grv.ID = "grid_view" + i;
grv.DataSource = dt;
grv.DataBind();
/* grv.Columns[0].ItemStyle.Width = new Unit("5%");
grv.Columns[1].ItemStyle.Width = new Unit("7%");
grv.Columns[2].ItemStyle.Width = new Unit("12%");
grv.Columns[3].ItemStyle.Width = new Unit("12%");
grv.Columns[4].ItemStyle.Width = new Unit("7%");
grv.Columns[5].ItemStyle.Width = new Unit("7%");
grv.Columns[6].ItemStyle.Width = new Unit("23%");
grv.Columns[7].ItemStyle.Width = new Unit("22%");
grv.Columns[8].ItemStyle.Width = new Unit("5%");*/
Label lblBlankLines = new Label();
lblBlankLines.Text = "<br />";
Panel panelGrid = new Panel();
panelGrid.ID = "panel_grid" + i;
Label lblTipo = new Label();
string tipoOcorrencia = lst[0]["Ocorrência"].ToString();
/*
* Capitalized
* TextInfo myTI = new CultureInfo("pt-BR", false).TextInfo;
string novoTipoOcorrencia = myTI.ToTitleCase(tipoOcorrencia);*/
int quantidade = lst.Count;
lblTipo.Text = " - " + tipoOcorrencia + ": " + quantidade;
LinkButton lkBtn = new LinkButton();
lkBtn.ID = "link_button" + i;
lkBtn.Text = "Exibir | Ocultar";
lkBtn.Attributes["onClick"] = "javascript:return ocultaGrid('" + panelGrid.ID + "'), false";
panel_status.Controls.Add(lblBlankLines);
panel_status.Controls.Add(lkBtn);
panel_status.Controls.Add(lblTipo);
panelGrid.Controls.Add(grv);
panel_status.Controls.Add(panelGrid);
panel_status.DataBind();
i++;
}
}
I've tried to get the columns, but i got an error, telling me an invalid index access.
How can i access my columns in that gridview?

Use the RowDataBound EventHandler:
Count your indexes and make sure you are not trying to access a non-existent column as well.
See link for an example:
http://msdn.microsoft.com/en-us/library/ms178296(v=vs.100).ASPX
grv.RowDataBound += grv_RowDataBound;
private void grv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Width = new Unit("5%");
e.Row.Cells[1].Width = new Unit("7%");
e.Row.Cells[2].Width = new Unit("12%");
e.Row.Cells[3].Width = new Unit("12%");
e.Row.Cells[4].Width = new Unit("7%");
e.Row.Cells[5].Width = new Unit("7%");
e.Row.Cells[6].Width = new Unit("23%");
e.Row.Cells[7].Width = new Unit("22%");
e.Row.Cells[8].Width = new Unit("5%");
}
}

Related

input data from datagridView into gMapControl

I have some problem with coding on C# with data from dataGridView.
I have some data table on dataGridView and I need to put this info into gMapControl using GMap.Net for creating of several markers on the map.
Here is my code:
private void gMapControl1_Load(object sender, EventArgs e)
{
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
GMap.NET.WindowsForms.GMapOverlay markersOverlay = new GMap.NET.WindowsForms.GMapOverlay(gMapControl1, "marker");
GMap.NET.WindowsForms.Markers.GMapMarkerGoogleGreen marker =
new GMap.NET.WindowsForms.Markers.GMapMarkerGoogleGreen(
new GMap.NET.PointLatLng(MyVar.lat, MyVar.lon));
gMapControl1.Position = new GMap.NET.PointLatLng(MyVar.lat, MyVar.lon);
marker.ToolTip = new GMap.NET.WindowsForms.ToolTips.GMapRoundedToolTip(marker);
marker.ToolTipText = "Home";
markersOverlay.Markers.Add(marker);
gMapControl1.Overlays.Add(markersOverlay);
}
This is pseudo code, that should get you going
var dgv = new DataGridView();
var str = dgv.Rows[0].Cells["Column Name here"]; //column name
var ord = dgv.Rows[0].Cells[0]; //column ordnal
var changeableValue = string.Empty;
foreach (DataGridViewRow row in dgv.Rows)
{
changeableValue = row.Cells[0].ToString(); // ordinal position again
}
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
GMapControl1.DragButton = Windows.Forms.MouseButtons.Left
GMapControl1.CanDragMap = True
If RadioButton1.Checked Then
' Form3.GMapControl1.MapProvider = GMapProviders.GoogleSatelliteMap
Form3.GMapControl1.MapProvider = GMapProviders.GoogleHybridMap
ElseIf RadioButton2.Checked Then
Form3.GMapControl1.MapProvider = GMapProviders.GoogleMap
ElseIf RadioButton3.Checked Then
Form3.GMapControl1.MapProvider = GMapProviders.GoogleTerrainMap
End If
Form3.GMapControl1.Position = New PointLatLng(35.502509, 2.916693)
Form3.GMapControl1.MinZoom = 0
Form3.GMapControl1.MaxZoom = 24
Form3.GMapControl1.Zoom = 7
Form3.GMapControl1.Dock = DockStyle.Fill
'GMapControl1.AutoScroll = True
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerAndCache
For j As Integer = 0 To DataGridView1.Rows.Count - 2
Dim marker As GMarkerGoogle = New GMarkerGoogle(New PointLatLng(DataGridView1.Rows(j).Cells(1).Value, DataGridView1.Rows(j).Cells(2).Value), GMarkerGoogleType.green)
' marker.ToolTipText = String.Format("réservoir " + DataGridView1.Rows(j).Cells(4).Value)
marker.ToolTipText = String.Format("Réservoir " + DataGridView1.Rows(j).Cells(8).Value + " m3 " + DataGridView1.Rows(j).Cells(4).Value)
markers.Markers.Add(marker)
Form3.GMapControl1.Overlays.Add(markers)
marker.ToolTipMode = MarkerTooltipMode.Always
Next
Return
End Sub

How to set focus on first image in my Panel?

Hi given below code sets focus on last image in my panel.
how do i set it to focus on first image?
I sort of understand i have to use ID of image button i create on fly. but don't know how.Please help.
var fileIdx = 0;
foreach (Tripclass Trip in TripsByTripIds )
{
fileIdx++;
ImageButton imageButton = new ImageButton(){ ID = "imageBtn" + fileIdx };
imageButton.ImageUrl = "~/" +Trip.CorridorName+"/"+Trip.Time+"/"+Trip.ImgFileName;
imageButton.Height = Unit.Pixel(100);
imageButton.Style.Add("padding", "5px");
imageButton.Width = Unit.Pixel(100);
imageButton.Click += new ImageClickEventHandler(imageButton_Click);
AMSPanel1.Controls.Add(imageButton);
AMSPanel1.Height = Unit.Pixel(860);
imageButton.Focus();
}
var fileIdx = 0;
foreach (Tripclass Trip in TripsByTripIds )
{
fileIdx++;
ImageButton imageButton = new ImageButton(){ ID = "imageBtn" + fileIdx };
imageButton.ImageUrl = "~/" +Trip.CorridorName+"/"+Trip.Time+"/"+Trip.ImgFileName;
imageButton.Height = Unit.Pixel(100);
imageButton.Style.Add("padding", "5px");
imageButton.Width = Unit.Pixel(100);
imageButton.Click += new ImageClickEventHandler(imageButton_Click);
AMSPanel1.Controls.Add(imageButton);
AMSPanel1.Height = Unit.Pixel(860);
if(fileIdx == 1)
{
imageButton.Focus();
}
}
The only thing changed is this:
From:
imageButton.Focus();
To:
if(fileIdx == 1)
{
imageButton.Focus();
}

Image is not displaying in browser

hey guys i am making an art website for my fiance but cant get the images to display and i am doing it exactly like in previews websites i made but using visual studio 2012 from 2008. Here is the code. I get the error sign in the image and not the correct image. It loads the path from the database witch is Art/1.jpg.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Home : System.Web.UI.Page
{
int Add = 1;
protected void Page_Init(object sender, EventArgs e)
{
Database s = new Database();
int Total = s.ArtCount(); //Count the total of cars int the database
for (int loop = Total; loop > 0; loop--)
{
Panel Panel1 = new Panel(); //Create a new panel for all the cars
Panel1.ID = "pnl" + loop.ToString();
Panel1.Style["position"] = "absolute";
Panel1.Style["left"] = "155px";
Panel1.Style["top"] = "400px";
Panel1.Style["Height"] = "200px";
Panel1.Style["Width"] = "1000px";
Panel1.BackColor = System.Drawing.Color.Black;
form1.Controls.Add(Panel1);
if (Add >= 2)
{
int Top = (400 * (Add - 1));
Panel1.Style["top"] = (250 + Top + 20).ToString() + "px"; //Set the second and more panels down
}
Add++;
string Art = s.LoadArt(loop);
string ArtID = Art.Substring(0, Art.IndexOf("|"));
Art = Art.Substring(ArtID.Length + 1);
string ArtName = Art.Substring(0, Art.IndexOf("|"));
Art = Art.Substring(ArtName.Length + 1);
string Description = Art.Substring(0, Art.IndexOf("|"));
Art = Art.Substring(Description.Length + 1);
string PicUrl = Art.Substring(0, Art.IndexOf("|"));
string path = Server.MapPath(PicUrl);
Image image1 = new Image();
image1.ID = "img" + ArtID +loop;
image1.ImageAlign = ImageAlign.AbsMiddle;
image1.Visible = true;
image1.ImageUrl = path;
image1.Style["Left"] = "10px";
image1.Style["position"] = "absolute";
image1.Style["top"] = "10px";
image1.Height = 180;
image1.Width = 230;
Panel1.Controls.Add(image1);
Label label1 = new Label(); //Create a label for the description of each car
label1.ID = "lblDescription" + ArtID;
label1.Text = Description;
label1.ForeColor = System.Drawing.Color.Lime;
label1.BorderStyle = BorderStyle.Groove;
label1.BorderColor = System.Drawing.Color.Violet;
label1.Style["Left"] = "500px";
label1.Style["position"] = "absolute";
label1.Style["top"] = "30px";
Panel1.Controls.Add(label1);
string View = s.TimesView(ArtID);
Label label10 = new Label(); //Create a label for the times each car is viewed
label10.ID = "lblView" + ArtID+loop;
label10.Text = "Times Viewed: " + View;
label10.ForeColor = System.Drawing.Color.Lime;
label10.Style["Left"] = "799px";
label10.Style["position"] = "absolute";
label10.Style["top"] = "170px";
Panel1.Controls.Add(label10);
Button btnView = new Button(); //Create a button to view a car for all cars
btnView.ID = ArtID;
btnView.Text = "View";
btnView.ForeColor = System.Drawing.Color.DeepSkyBlue;
btnView.BackColor = System.Drawing.Color.Gray;
btnView.BorderColor = System.Drawing.Color.Violet;
btnView.Style["top"] = "150px";
btnView.Style["left"] = "800px";
btnView.Style["Height"] = "20px";
btnView.Style["position"] = "absolute";
btnView.BorderStyle = BorderStyle.Outset;
btnView.Command += new CommandEventHandler(btnView_Command); //Create a command EventHandler to now what button was clicked
btnView.CommandArgument = ArtID; //Set the commandArguments = to the carID
Panel1.Controls.Add(btnView);
}
}
void btnView_Command(object sender, CommandEventArgs e)
{
string ArtID = e.CommandArgument.ToString(); //Gets theCarId from the CommandArgument
Session["ArtID"] = ArtID; //Create session CarID and set it = to the CarID
Response.Redirect("ViewArt.aspx"); //Redirect to the ViewCar page
}
}

Open XML Word C# - Split into Two Columns

I was wondering how would it be possible to split the word document into two columns. The reason why I want to do this is because I want to be able to fit all of the information on one page.
Thank you so much for your help and time!
My Code
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document();
var margin_size = 100;
PageMargin pargeMargins = new PageMargin();
pargeMargins.Top = margin_size;
pargeMargins.Bottom = margin_size;
SectionProperties sectionProps = new SectionProperties();
sectionProps.Append(pargeMargins);
Body body = mainPart.Document.AppendChild(new Body());
body.Append(sectionProps);
ParagraphProperties paragraphProperties = new ParagraphProperties
(
//new ParagraphStyleId() { Val = "No Spacing" },
new SpacingBetweenLines() { After = "0" }
);
Paragraph para_main = body.AppendChild(new Paragraph(paragraphProperties));
// Creating the Header where the Serial Number will exist
// Serial Number
Run run_mainHeader = para_main.AppendChild(new Run());
RunProperties runProp_mainHeader = new RunProperties(); // Create run properties.
FontSize size_mainHeader = new FontSize();
size_mainHeader.Val = new StringValue("48");
runProp_mainHeader.Append(size_mainHeader);
run_mainHeader.Append(runProp_mainHeader); // Append all of the properties
run_mainHeader.Append(new Text("S/N: " + sn));
// Serial Barcode
Run run_barcode = para_main.AppendChild(new Run());
RunProperties runProp_barcode = new RunProperties(); // Create run properties.
RunFonts runFontMain_barcode = new RunFonts(); // Create font
runFontMain_barcode.Ascii = "Code39AzaleaNarrow1"; // Specify font family
FontSize size_barcode = new FontSize();
size_barcode.Val = new StringValue("48");
runProp_barcode.Append(runFontMain_barcode);
runProp_barcode.Append(size_barcode);
run_barcode.PrependChild<RunProperties>(runProp_barcode);
sn = sn.ToUpper(); // Sets all the values to uppercase to be a barcode format
run_barcode.AppendChild(new Text("*" + sn + "*"));
run_barcode.AppendChild(new Break());
// Tube Type
Run run_tubetype = para_main.AppendChild(new Run());
RunProperties runProp_tubetype = new RunProperties(); // Create run properties.
FontSize size_tubetype = new FontSize();
size_tubetype.Val = new StringValue("38");
runProp_tubetype.Append(size_tubetype);
run_tubetype.Append(runProp_tubetype); // Append all of the properties
run_tubetype.Append(new Text("Tube Type: " + forms[0].TubeType + " "));
//run_tubetype.Append(new Break());
// Tube Barcode
Run run_barcode_tube = para_main.AppendChild(new Run());
RunProperties runProp_barcode_tube = new RunProperties(); // Create run properties.
RunFonts runFontMain_barcode_tube = new RunFonts(); // Create font
runFontMain_barcode_tube.Ascii = "Code39AzaleaNarrow1"; // Specify font family
FontSize size_barcode_tube = new FontSize();
size_barcode_tube.Val = new StringValue("48");
runProp_barcode_tube.Append(runFontMain_barcode_tube);
runProp_barcode_tube.Append(size_barcode_tube);
run_barcode_tube.PrependChild<RunProperties>(runProp_barcode_tube);
sn = sn.ToUpper(); // Sets all the values to uppercase to be a barcode format
run_barcode_tube.AppendChild(new Text("*" + forms[0].TubeType + "*"));
run_barcode_tube.AppendChild(new Break());
// Goes through all of the forms
foreach (var form in forms)
{
// Set up a header per form
Run run_header = para_main.AppendChild(new Run());
RunProperties runProp_formHeader = new RunProperties();
Bold bold = new Bold();
Underline ul = new Underline() { Val = DocumentFormat.OpenXml.Wordprocessing.UnderlineValues.Single };
FontSize size_formHeader = new FontSize();
size_formHeader.Val = new StringValue("24");
runProp_formHeader.Append(size_formHeader);
runProp_formHeader.Append(bold);
runProp_formHeader.Append(ul);
run_header.AppendChild(new RunProperties(runProp_formHeader));
//run_header.AppendChild(new RunProperties(new Bold(), new Underline()));
string username = form.Username;
string proces_header = form.HeaderTitle;
run_header.AppendChild(new Text(proces_header));
run_header.AppendChild(new Break());
// Goes through all of the fields that each form contains.
for (int i = 0; i < form.FieldList.Count; i++)
{
// Do not need to print out user or serial for each form.
if (!(form.FieldList[i].Token == "SNT"))
{
Run run_data = para_main.AppendChild(new Run());
if (form.FieldList[i].Default)
{
run_data.AppendChild(new Text(form.FieldList[i].Label));
}
else
{
run_data.AppendChild(new Text(form.FieldList[i].Label + " " + form.FieldList[i].Spec + form.FieldList[i].Value));
}
run_data.AppendChild(new Break());
}
}
}
mainPart.Document.Save();
wordDoc.Close();
return "Success";
}
Currently the code prints out everything top-down on one column. And I want it with two columns
You can two or how many columns you want using the Columns Class for the SectionProperties and ParagraphProperties Class
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.columns(v=office.14).aspx
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.paragraphproperties(v=office.14).aspx
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.sectionproperties(v=office.14).aspx
This should do it:
// Add a new main document part.
package.AddMainDocumentPart();
// Create the Document DOM.
package.MainDocumentPart.Document = new Document();
Body bd = package.MainDocumentPart.Document.Body = new Body();
//write a first paragraph on two columns
var paragrap1 = new Paragraph();
var paragraphSectionProperties = new ParagraphProperties(new SectionProperties());
var paragraphColumns = new Columns();
paragraphColumns.EqualWidth = true;
paragraphColumns.ColumnCount = 2;
paragraphSectionProperties.Append(paragraphColumns);
paragrap1.Append(paragraphSectionProperties);
paragrap1.Append(new Run(new Text(str)));
bd.AppendChild(paragrap1);
//write another paragraph without paragraph properties
bd.Append(new Paragraph(new Run(new Text(str))));
//set the body properties default three columns
var sectionProperties = new SectionProperties();
var columns = new Columns();
columns.EqualWidth = true;
columns.ColumnCount = 3;
sectionProperties.Append(columns);
bd.Append(sectionProperties);
package.MainDocumentPart.Document.Save();
You can do it for the complete document with this code:
var sectionProperty = document.Body.Descendants<SectionProperties>().First();
var paragraphColumns = new Columns {EqualWidth = true, ColumnCount = 2};
sectionProperty.Append(paragraphColumns);
Try with..
Word.Application WordApp = new Word.Application();
Word.Document BaseDoc = default(Word.Document);
Word.Document DestDoc = default(Word.Document);
int intNumberOfPages = 0;
string intNumberOfChars = null;
int intPage = 0;
//Word Constants
const var wdGoToPage = 1;
const var wdStory = 6;
const var wdExtend = 1;
const var wdCharacter = 1;
//Show WordApp
WordApp.ShowMe();
//Load Base Document
BaseDoc = WordApp.Documents.Open(Filename);
BaseDoc.Repaginate();
//Loop through pages
intNumberOfPages = BaseDoc.BuiltInDocumentProperties("Number of Pages").value;
intNumberOfChars = BaseDoc.BuiltInDocumentProperties("Number of Characters").value;
for (intPage = 1; intPage <= intNumberOfPages; intPage++) {
if (intPage == intNumberOfPages) {
WordApp.Selection.EndKey(wdStory); }
else {
WordApp.Selection.GoTo(wdGoToPage, 2);
Application.DoEvents();
WordApp.Selection.MoveLeft(Unit = wdCharacter, Count = 1);
}
Application.DoEvents();
WordApp.Selection.HomeKey(wdStory, wdExtend);
Application.DoEvents();
WordApp.Selection.Copy();
Application.DoEvents();
//Create New Document
DestDoc = WordApp.Documents.Add;
DestDoc.Activate();
WordApp.Selection.Paste();
DestDoc.SaveAs(NewFileName + intPage.ToString + ".doc");
DestDoc.Close();
DestDoc = null;
WordApp.Selection.GoTo(wdGoToPage, 2);
Application.DoEvents();
WordApp.Selection.HomeKey(wdStory, wdExtend);
Application.DoEvents();
WordApp.Selection.Delete();
Application.DoEvents();
}
BaseDoc.Close(false);
BaseDoc = null;
WordApp.Quit();
WordApp = null;

How to create method for a dynamically added button. asp.net C#

I created a button that is supposed to view a message in a updatepanel.
I dynamically added through code since the ammount of buttons are relative to how many messages they recieve. I need the button to display a label. Any Ideas?
Here is my code:
I feel like the problem that the scope is limited to the loop. I was going to change the id to increase "lblbody" = 1+=1
$ while (reader.Read())
{
string strrecipient, strsender, strsubject, strbody, strdate, strviewstate;
strdate = "Date Sent: " + reader["date"].ToString();
strsender = "From: " + reader["sender"].ToString();
strsubject = "Subject: " + reader["subject"].ToString();
strbody = reader["body"].ToString();
strrecipient = "To: " + reader["recipient"].ToString();
if (reader["viewstate"].ToString() == "notread")
{
strviewstate = "UnRead";
}
else
{
strviewstate = "read";
}
string strName;
int intName;
intName = 0;
strName = intName.ToString();
Panel pnlNewMess = new Panel();
pnlMess.Controls.Add(pnlNewMess);
pnlNewMess.BorderColor = System.Drawing.Color.LightGray;
pnlNewMess.BorderStyle = BorderStyle.Solid;
pnlNewMess.BorderWidth = 1;
Label lbldate = new Label();
Label lblsender = new Label();
Label lblsubject = new Label();
Label lblbody = new Label();
Label lblrecipient = new Label();
Label lblviewstate = new Label();
Button btnView = new Button();
lbldate.Text = strdate;
lblsender.Text = strsender;
lblsubject.Text = strsubject;
lblbody.Text = strbody;
lblrecipient.Text = strrecipient;
lblviewstate.Text = strviewstate;
btnView.Text = "View Message";
btnView.ID = strsubject;
lblbody.Visible = false;
lblrecipient.Visible = false;
lblviewstate.Visible = false;
//lblbody.ID = "lblBody" + strName;
pnlNewMess.Controls.Add(lblrecipient);
pnlNewMess.Controls.Add(new LiteralControl("<br />"));
if (lblviewstate.Text == "notread")
{
pnlNewMess.Controls.Add(new LiteralControl("<div class='clsmess' style='background-image:url('images/unread.png'); color:white;'>"));
}
else
{
pnlNewMess.Controls.Add(new LiteralControl("<div class='clsmess' style='background-image:url('images/read.png'); color:white;'>"));
}
pnlNewMess.Controls.Add(lbldate);
pnlNewMess.Controls.Add(lblsubject);
pnlNewMess.Controls.Add(lblsender);
pnlNewMess.Controls.Add(btnView);
pnlNewMess.Controls.Add(new LiteralControl("</div>"));
pnlNewMess.Controls.Add(lblviewstate);
pnlNewMess.Controls.Add(new LiteralControl("<br />"));
pnlView.Controls.Add(lblbody);
pnlMess.Controls.Add(pnlNewMess);
}
The only thing I have tried was to set a click event for the button taking the subject lbl.text to a global variabe and then with the click of another button, would compare the subject field with the database and display the lblbody.
btnview.text = lblsubject.text;
SqlCommand CMretMess = new SqlCommand("SELECT body FROM [message] WHERE subject='" + clsGlobals.myGlobals.strSub + "'", connection);
lblBody.Text = CMretMess.ExecuteScalar().ToString();
connection.Close();
Could you do something as simple as this?
btnView.Click += (sender, e) => {
lblbody.Visible = true;
};

Categories